熊猫-如何比较2个系列并将两个系列中的值附加到列表中

时间:2018-07-18 14:37:16

标签: python pandas

我写了代码,其中有一个包含所有食物的数据框。然后,我使用str.contains将其分为水果和蔬菜系列。我编写了代码,在其中将两个系列中常见的食物添加到列表中:

fruit = fruit_2.tolist()#converting the series to a list
veg = veg_2.tolist()#converting the series to a list

for x in range (len(fruit)):
    for y in range (len(veg)):
        if fruit[x] == veg[y]:
            both.append(fruit[x]) 
print(both)

这只是想知道是否有人有使用熊猫的解决方案而不使用for循环。 谢谢

2 个答案:

答案 0 :(得分:0)

尝试一下:

fruit_2[fruit_2.isin(veg_2)]

这将为您提供常见元素。

答案 1 :(得分:0)

您可以使用np.intersect1d

import numpy as np

# gives a numpy array (you can later convert to series or list)
both = np.intersect1d(fruit_2, veg_2)  

answer

提供