如何比较两排Pandas系列?

2024-05-19 12:36:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我有两个python pandas系列df10df5。我想比较它们的值。例如:df10[-1:]< df5[-1:],它返回true。df10[-2:-1] > df5[-2:-1],返回false。

但如果我把它们组合在一起,df10[-1:]< df5[-1:] and df10[-2:-1]>df5[-2:-1],它就会返回

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

但我希望它返回错误。我怎样才能解决这个问题?


Tags: andofthefalsetruepandasisvalue
2条回答

您可以使用pandas系列values属性执行此操作:

if (df10.values[-2:-1] > df5.values[-2:-1]) and\ 
        (df10.values[-1:] < df5.values[-1:]):
    print("we met the conditions!")

假设您有来自此程序的两个数据帧:

# Python 3.5.2
import pandas as pd
import numpy as np

# column names for example  dataframe
cats = ['A', 'B', 'C', 'D', 'E']

df5 = pd.DataFrame(data = np.arange(25).reshape(5, 5), columns=cats)
print("Dataframe 5\n",df5,"\n")

df10=pd.DataFrame(data = np.transpose(np.arange(25).reshape(5, 5)), columns=cats)
print("Dataframe 10\n",df10)

产生的数据帧是:

Dataframe 5
     A   B   C   D   E
0   0   1   2   3   4
1   5   6   7   8   9
2  10  11  12  13  14
3  15  16  17  18  19
4  20  21  22  23  24 

Dataframe 10
    A  B   C   D   E
0  0  5  10  15  20
1  1  6  11  16  21
2  2  7  12  17  22
3  3  8  13  18  23
4  4  9  14  19  24

现在让我们看看第一次比较的结果:

print(df5[-1:])
print(df10[-1:])

a=df10[-1:]< df5[-1:]

print("\n",a,"\n",type(a))

结果是:

    A   B   C   D   E
4  20  21  22  23  24
   A  B   C   D   E
4  4  9  14  19  24

       A     B     C     D      E
4  True  True  True  True  False 
 <class 'pandas.core.frame.DataFrame'>

第二个比较:

print(df5[-2:-1])
print(df10[-2:-1])

b=df10[-2:-1]>df5[-2:-1]
print("\n",b,"\n",type(b))

结果是:

    A   B   C   D   E
3  15  16  17  18  19
   A  B   C   D   E
3  3  8  13  18  23

        A      B      C      D     E
3  False  False  False  False  True 
 <class 'pandas.core.frame.DataFrame'>

问题:

如果我们评估:

pd.Series([True, True, False, False]) and pd.Series([False, True, False, True])

正确答案是什么?以下内容:

  1. pd.Series([False, True, False, False])
  2. False
  3. True
  4. 以上都是
  5. 以上任何一项
  6. 这取决于

答案是:6-这要看情况而定。这取决于你想要什么。

首先,我们必须创建用于比较的布尔序列:

a_new = (df10[-1:] < df5[-1:]).any()
print(a_new,"\n",type(a_new))

b_new = (df10[-2:-1] > df5[-2:-1]).any()
print("\n",b_new,"\n",type(b_new))

结果是:

A     True
B     True
C     True
D     True
E    False
dtype: bool 
 <class 'pandas.core.series.Series'>

A    False
B    False
C    False
D    False
E     True
dtype: bool 
 <class 'pandas.core.series.Series'>

现在,我们可以计算3个案例。

情况1:a.any()和b.any()

a.any() = True if any item in a is True
b.any() = True if any item in b is True
print(a_new.any() and b_new.any())

结果为真。

案例2:a.all()和b.all()

a.all() = True if every item in a is True   
b.all() = True if every item in b is True
print(a_new.all() and b_new.all())

结果为假。

案例3:成对比较

为此,必须将每个元素相互比较。

result_pairwise = [a_new and b_new for a_new, b_new in zip(a_new,b_new)]
print(result_pairwise,"\n",type(result_pairwise))

结果是:

[False, False, False, False, False] 
 <class 'list'>

有关详细信息:

相关问题 更多 >