【问题标题】:How to return the values If One List Against Another Dataframe (Pandas)?如果一个列表针对另一个数据框(熊猫),如何返回值?
【发布时间】:2019-04-13 05:27:06
【问题描述】:
df1=pd.DataFrame({'Product_ID':["55165","80125,30215","55557","92361","32619,28965,20147","88722","82793","70809, 20201","11367"],
          'Product': ["ABC",'FDA','FSD','JGH','TYE','BVC','LKJ','HJD','POI'],
         'Country':['CN','US','GB','AG','MX','CA','DE','CA','SG']})

df2=pd.DataFrame({'Deal_ID':[70809,88722,82793,20201,55165,30215,11367]})

上面提供了df和列表(deal_id)。

我想返回国家信息和添加到 df2 的 product_id。 我尝试使用 join 函数,但 df1 的 Product_ID 不是数字。有什么解决办法吗?

提前感谢您的帮助。

【问题讨论】:

标签: python pandas dataframe contains


【解决方案1】:

您可以通过几个步骤来做到这一点:-

1。展平您的聚合数据框

根据需要链接和重复系列,记住将str转换为int

from itertools import chain
import numpy as np

split = df1['Product_ID'].str.split(',')
lens = split.map(len)

df1 = pd.DataFrame({'Country': np.repeat(df1['Country'], lens),
                    'Product': np.repeat(df1['Product'], lens),
                    'Deal_ID': list(map(int, chain.from_iterable(split)))})

2。与包含选定 Deal_ID 的数据框合并

df2 = df2.merge(df1)

print(df2)

   Deal_ID Country Product
0    70809      CA     HJD
1    88722      CA     BVC
2    82793      DE     LKJ
3    20201      CA     HJD
4    55165      CN     ABC
5    30215      US     FDA
6    11367      SG     POI

【讨论】:

  • 嗨@jpp,有没有像“包含”函数并返回完整的Product_ID的方法?我不想要拆分列表。谢谢
  • @Boomshakalaka,不,没有基于“包含”的“内置合并”。而且,如果你自己写这样一个函数,那将是混乱和低效的。
  • 好的。谢谢!!
猜你喜欢
  • 1970-01-01
  • 2019-06-10
  • 2017-12-08
  • 2022-01-23
  • 1970-01-01
  • 2019-01-20
  • 2021-07-15
  • 2021-06-26
  • 2013-12-04
相关资源
最近更新 更多