英文:
Python if statement getting: 'The truth value of a Series is ambiguous'
问题
Condition worked independently, but adding as part of an if
, is getting truth ambiguous:
import pandas as pd
import numpy as np
df1 = pd.DataFrame(np.random.randn(10,5), columns=list('ABCDE'))
df1
# df1.loc[(df1.D > 1.25) | (df1.D < -0.25)] # work
# df1.loc[:,'D'] > 0.1 # work
if df1.loc[:,'D'] > 0.1:
print(df1['A'] * df1['B'])
英文:
Condition worked independently, but adding as part of an if
, is getting truth ambiguous:
import pandas as pd
import numpy as np
df1 = pd.DataFrame(np.random.randn(10,5), columns=list('ABCDE'))
df1
# df1.loc[(df1.D > 1.25) | (df1.D < -0.25)] # work
# df1.loc[:,'D'] > 0.1 # work
if df1.loc[:,'D'] > 0.1:
print(df1['A'] * df1['B'])
答案1
得分: 1
df.loc[:, 'D'] > 0.1
会给你一个包含 True 和 False 值的向量:
Out[1]:
0 False
1 False
2 False
3 False
4 True
5 True
6 False
7 False
8 False
9 False
Name: D, dtype: bool
不确定如何将一个包含 True 和 False 的向量转换为单个值。你可以考虑全部为真时:if (df1.loc[:, 'D'] > 0.1).all():
,任意为真时:if (df1.loc[:, 'D'] > 0.1).any():
,或进行迭代:
for item in (df1.loc[:, 'D'] > 0.1):
if item:
print('something')
在不了解更多关于你尝试做什么的情况下,Python 和我只是在猜测。
所以根据你的编辑,我认为你想要将 A 和 B 相乘,并在 D > 0.1
时获取这些值,这很简单:
(df1['A'] * df1['B'])[(df1.loc[:, 'D'] > 0.1)]
1 -0.590544
3 -0.371079
8 -0.704530
dtype: float64
英文:
df.loc[:,'D'] > 0.1
gives you a vector of true and false values:
Out[1]:
0 False
1 False
2 False
3 False
4 True
5 True
6 False
7 False
8 False
9 False
Name: D, dtype: bool
It's not sure how to convert a vector of true and false into a single value. You could assume all: if (df1.loc[:,'D'] > 0.1).all():
, any: if (df1.loc[:,'D'] > 0.1).any():
, or iterate through:
for item in (df1.loc[:,'D'] > 0.1):
if item:
print('something')
Without knowing more about what you're trying to do python and I are just guessing.
So looking at your edit, I think you're trying to multiply A and B and take the values when D > 0.1
, which is easy:
(df1['A'] * df1['B'])[(df1.loc[:,'D'] > 0.1)]
1 -0.590544
3 -0.371079
8 -0.704530
dtype: float64
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论