首页 > 解决方案 > 大熊猫在大熊猫的两列之间找到共同值的索引

问题描述

我有一个如下所示的数据框:df1

Date and time   Price1  PrePrice
17.9.2018 9:47  1200.6  1204.8
17.9.2018 9:47  1200.6  1203.8
17.9.2018 9:47  1200.6  1202.1
17.9.2018 9:47  1200.6  1204.8
17.9.2018 9:47  1200.6  1204.8
17.9.2018 9:47  1200.6  1204.8
17.9.2018 9:47  1202.1  1204.8
17.9.2018 23:30 1200.7  1204.8
17.9.2018 23:31 1200.7  1204.8
17.9.2018 23:32 1200.6  1204.8
17.9.2018 23:33 1200.6  1204.8
17.9.2018 23:36 1200.7  1204.8
17.9.2018 23:47 1200.7  1204.8
17.9.2018 23:48 1200.6  1202.1
17.9.2018 23:50 1202.1  1200.9
17.9.2018 23:52 1203.8  1200.8
17.9.2018 23:55 1204.8  1200.7

我想像这样获得两列 Price1,PrePrice 之间的共同值:(1204.8; 17.9.2018 9:47; 17.9.2018 23:55) 它尝试了这种方法,但速度很慢:

c = [(i, j)  for i, x in enumerate(a) for j, y in enumerate(b) if x == y]

标签: pythonpandas

解决方案


如果您想要它们在同一行上相等的地方,这是香草熊猫:

df1[df1.Price1 == df1.PrePrice]

(您的示例中没有。)

如果您想要所有共享值,您可以使用集合表示法:

c = set(df1.Price1).intersection(df1.PrePrice)
print(c)
> {1200.7, 1202.1, 1203.8, 1204.8}

鉴于这些时间,您可以过滤Date and Timewith Price1

df1[df1.Price1.isin(c)][['Date and time', 'Price1']]

    Date and time   Price1
6   17.9.2018 9:47      1202.1
7   17.9.2018 23:30     1200.7
8   17.9.2018 23:31     1200.7
11  17.9.2018 23:36     1200.7
12  17.9.2018 23:47     1200.7
14  17.9.2018 23:50     1202.1
15  17.9.2018 23:52     1203.8
16  17.9.2018 23:55     1204.8

推荐阅读