i.n*_*n.m 7 python logic pandas
我知道之前已经问过这个问题,但是,当我试图做一个if
声明并且我收到错误时.我查看了这个链接,但在我的情况下没有多大帮助.我dfs
是一个DataFrame列表.
我正在尝试以下方式,
for i in dfs:
if (i['var1'] < 3.000):
print(i)
Run Code Online (Sandbox Code Playgroud)
给出以下错误:
ValueError:Series的真值是不明确的.使用a.empty,a.bool(),a.item(),a.any()或a.all().
和我尝试以下,并得到同样的错误.
for i,j in enumerate(dfs):
if (j['var1'] < 3.000):
print(i)
Run Code Online (Sandbox Code Playgroud)
我的var1
数据类型是float32
.我没有使用任何其他logical
运营商和&
或|
.在上面的链接中,似乎是因为使用了逻辑运算符.我为什么要这样ValueError
?
这是一个小型演示,它说明了为什么会这样:
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
Run Code Online (Sandbox Code Playgroud)
当我们试图检查这样的系列是否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().
Run Code Online (Sandbox Code Playgroud)
解决方法:
我们可以决定如何处理布尔值的系列-比如if
应该返回True
,如果所有的值是True
:
In [136]: res.all()
Out[136]: False
Run Code Online (Sandbox Code Playgroud)
或者当至少一个值为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
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
17224 次 |
最近记录: |