2017-08-03 88 views
1

我知道這個問題之前已經被問過了,但是,當我嘗試執行if語句並且出現錯誤時。我看着這個link,但對我的情況沒有太大的幫助。我的dfs是一個DataFrames列表。錯誤:一個系列的真值不明確 - Python熊貓

我想下面,

for i in dfs: 
    if (i['var1'] < 3.000): 
     print(i) 

提供了以下錯誤:

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

我嘗試以下,並得到同樣的錯誤。

for i,j in enumerate(dfs): 
    if (j['var1'] < 3.000): 
     print(i) 

我的var1數據類型是float32。我沒有使用任何其他logical運營商和&|。在上面的鏈接中,似乎是因爲使用了邏輯運算符。我爲什麼得到ValueError

+0

做列表中的所有DF只有一排? – MaxU

+1

何時應該如果是真的?從那一刻起至少有一個這樣的排?或者從所有值都小於3的時刻開始? –

+0

在這種情況下,它不清楚 - 你在'如果...'比較什麼? – MaxU

回答

4

這裏是一個小的演示,這說明了爲什麼這是happenning:

In [131]: df = pd.DataFrame(np.random.randint(0,20,(5,2)), columns=list('AB')) 

In [132]: df 
Out[132]: 
    A B 
0 3 11 
1 0 16 
2 16 1 
3 2 11 
4 18 15 

In [133]: res = df['A'] > 10 

In [134]: res 
Out[134]: 
0 False 
1 False 
2  True 
3 False 
4  True 
Name: A, dtype: bool 

,當我們試圖檢查是否這種系列是True - 熊貓不知道該怎麼做:

In [135]: if res: 
    ...:  print(df) 
    ...: 
--------------------------------------------------------------------------- 
ValueError        Traceback (most recent call last) 
... 
skipped 
... 
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all(). 

解決方法:

我們可以決定如何處理布爾值的系列 - 例如if應該返回True如果所有True

In [136]: res.all() 
Out[136]: False 

,或者當至少一個值爲True:

In [137]: res.any() 
Out[137]: True 

In [138]: if res.any(): 
    ...:  print(df) 
    ...: 
    A B 
0 3 11 
1 0 16 
2 16 1 
3 2 11 
4 18 15 
+0

這個解釋很有幫助。 –

+0

@ i.n.n.m,謝謝! – MaxU

1

目前,您正在選擇整個系列進行比較。您可以通過一系列的個人價值,你要使用的東西線沿線的:

for i in dfs: 
if (i['var1'].iloc[0] < 3.000): 
    print(i) 

比較每個單獨的元素,你可以使用series.iteritems(文檔是稀疏在這一個),像這樣:

for i in dfs: 
    for _, v in i['var1'].iteritems(): 
     if v < 3.000: 
      print(v) 

更好的解決方案這裏大多數情況下是選擇數據框的子集,無論你需要什麼,像這樣使用的:在p和

for i in dfs: 
    subset = i[i['var1'] < 3.000] 
    # do something with the subset 

性能因爲在使用串行操作而不是迭代單個值時,大型數據幀的速度要快得多。欲瞭解更多詳情,您可以檢查出大熊貓documentation on selection.