Python if语句出现问题:’Series的真值是不明确的’

huangapple go评论62阅读模式
英文:

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'])

reference:
https://stackoverflow.com/questions/36921951/truth-value-of-a-series-is-ambiguous-use-a-empty-a-bool-a-item-a-any-o

英文:

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(&#39;ABCDE&#39;))
df1
# df1.loc[(df1.D &gt; 1.25) | (df1.D &lt; -0.25)] # work
# df1.loc[:,&#39;D&#39;] &gt; 0.1 # work
if df1.loc[:,&#39;D&#39;] &gt; 0.1:
    print(df1[&#39;A&#39;] * df1[&#39;B&#39;])

reference:
https://stackoverflow.com/questions/36921951/truth-value-of-a-series-is-ambiguous-use-a-empty-a-bool-a-item-a-any-o

答案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[:,&#39;D&#39;] &gt; 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[:,&#39;D&#39;] &gt; 0.1).all():, any: if (df1.loc[:,&#39;D&#39;] &gt; 0.1).any():, or iterate through:


for item in (df1.loc[:,&#39;D&#39;] &gt; 0.1):
    if item:
        print(&#39;something&#39;)

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 &gt; 0.1, which is easy:

(df1[&#39;A&#39;] * df1[&#39;B&#39;])[(df1.loc[:,&#39;D&#39;] &gt; 0.1)]

1   -0.590544
3   -0.371079
8   -0.704530
dtype: float64

huangapple
  • 本文由 发表于 2023年6月4日 23:58:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/76401262.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定