【问题标题】:How to find the matched info for all the elements in the list in pandas如何在熊猫列表中查找所有元素的匹配信息
【发布时间】:2018-05-11 16:13:22
【问题描述】:

我想查找列表中所有元素的匹配信息。例如:

df=pd.DataFrame({'ID':['1','2'],'Fruit':['apple|banana','banana|watermelon']})
        Fruit             ID
0   apple|banana           1
1   banana|watermelon      2

我还有一个带有水果价格的数据集:

price=pd.DataFrame({'Fruit':['apple','banana','watermelon','pear'],
                    'price':['1.49','0.59','5.99','1.99']})
    Fruit       price
0   apple       1.49
1   banana      0.59
2   watermelon  5.99
3   pear        1.99

我想在水果清单上找到所有匹配的价格:

         Fruit          ID  price
0   apple|banana        1   1.49|0.59
1   banana|watermelon   2   0.59|5.99

我知道我可以使用左连接来查找单个元素的匹配信息。我不确定如何找到所有匹配的信息。

有什么建议吗?

【问题讨论】:

  • 以下答案有帮助吗?如果是这样,请随时接受或要求澄清。

标签: python pandas dataframe lookup


【解决方案1】:

这是使用列表推导的一种方式:

s = price.set_index('Fruit')['price']

df['price'] = ['|'.join(list(map(s.get, i))) for i in df['Fruit'].str.split('|')]

print(df)

               Fruit ID      price
0       apple|banana  1  1.49|0.59
1  banana|watermelon  2  0.59|5.99

【讨论】:

  • 还有一个问题,它确实适用于这个示例数据。但是,当我应用我的大数据时,它得到了一个错误“TypeError: sequence item 2: expected str instance, NoneType found”。你知道可能的原因吗?谢谢!
  • @Lily,好像你的数据中有None。不过,我不确定在哪里,所以我不想猜测。如果您发现问题,您可以edit您的问题。否则,请参阅here。
  • 你是对的。我在stackoverflow.com/questions/25222697/… 找到了解决方案
猜你喜欢
  • 2013-12-06
  • 2021-07-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-06-12
  • 1970-01-01
  • 2018-07-11
  • 2013-08-22
相关资源
最近更新 更多