【问题标题】:Pandas - how to compare 2 series and append the values which are in both to a listPandas - 如何比较两个系列并将两者中的值附加到列表中
【发布时间】:2018-07-18 14:37:15
【问题描述】:

我已经编写了代码,其中有一个包含所有类型食物的数据框。然后,我使用 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)

这只是想知道是否有人有一个使用 pandas 并且不使用 for 循环的解决方案。 谢谢

【问题讨论】:

标签: python pandas


【解决方案1】:

试试这个:

fruit_2[fruit_2.isin(veg_2)]

这将为您提供通用元素。

【讨论】:

  • 该列表比我预期的要长,因为它返回的值比我之前的代码多,你会说我的代码不正确吗?。
  • 不,我认为重复项已被过滤掉。如果您想确认一下,只需这样做c=fruit_2[fruit_2.isin(veg_2)]len(c[c.duplicated(keep=False)]
  • 当我运行这个时,长度返回 0,这是否意味着没有重复?
  • 是的。没有重复。
【解决方案2】:

你可以使用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

【讨论】:

  • 我认为这可行,将其转换为系列的语法是什么?
  • both_series = pd.Series(both)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-01-30
  • 1970-01-01
  • 1970-01-01
  • 2015-07-09
  • 2023-01-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多