布尔比较多个数据帧

问题描述 投票:2回答:2

我有一个问题,我想比较多个数据帧的值。这是一个片段示例:

data0 = [[1,'01-01'],[2,'01-02']]
data1 = [[11,'02-30'],[12,'02-25']]
data2 = [[8,'02-30'],[22,'02-25']]
data3 = [[7,'02-30'],[5,'02-25']]
df0 = pd.DataFrame(data0,columns=['Data',"date"])
df1 = pd.DataFrame(data1,columns=['Data',"date"])
df2 = pd.DataFrame(data2,columns=['Data',"date"])
df3 = pd.DataFrame(data3,columns=['Data',"date"])
result=(df0['Data']| df1['Data'])>(df2['Data'] | df3['Data'])

我希望可以看到的是,如果df0 rowXdf1 rowX中的值大于df2 rowXdf3 rowX返回True,则应该是false。在上面的代码中,df1中的11大于8和7(分别为df2和3),因此结果应为True,然后对于第二行,2或12都不大于22(df2),因此应为False。但结果给了我

False,False

代替

True,False

任何想法或帮助?

python python-3.x pandas dataframe
2个回答
2
投票

问题

对于您的数据:

>>> df0['Data']
0    1
1    2
Name: Data, dtype: int64
>>> df1['Data']
0    11
1    12
Name: Data, dtype: int64

你做一点点或用|

>>> df0['Data']| df1['Data']
0    11
1    14
Name: Data, dtype: int64
>>> df2['Data']| df3['Data']
0    15
1    23
Name: Data, dtype: int64

为单个数字执行此操作:

>>> 1 | 11
11
>>> 2 | 12
14

这不是你想要的。

您可以使用np.maximum查找每个系列中的最大值:

>>> np.maximum(df0['Data'], df1['Data']) > np.maximum(df2['Data'], df3['Data'])
0     True
1    False
Name: Data, dtype: bool

1
投票

您现有的解决方案不起作用,因为|运算符对元素执行按位OR运算。

df0.Data | df1.Data

0    11
1    14
Name: Data, dtype: int64

这会导致您比较与数据框列中的值不同的值。总之,您的方法不会像您期望的那样比较值。


您可以通过查找 -

  • 每排df0df1,和
  • 每排最大的df2df3

比较这两列以检索结果 -

i = np.max([df0.Data, df1.Data], axis=0)
j = np.max([df2.Data, df3.Data], axis=0)

i > j
array([ True, False], dtype=bool)

对于任何数量的数据帧,这种方法都具有极高的可扩展性。

© www.soinside.com 2019 - 2024. All rights reserved.