2017-08-03 86 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.