将数据帧与数组合并?

2024-03-29 13:33:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我希望您能提供一些指导-我正在使用pythonv2.7中的Pandas库编写一个脚本。你知道吗

脚本的一部分合并了两个数据帧—一个用于收入,另一个用于性能数据。这些df都有每日条目,并且通过ID列链接。你知道吗

性能数据帧:

     RevID         Date       PartnerName        Performance        Revenue
     1,2           1/2/2015   Johndoe            0.02               0.00
     1             2/2/2015   Johndoe            0.12               0.00
     4             3/2/2015   Johndoe            0.10               0.00

请注意,上一行中的“1,2”是指需要添加在一起的两个ID

收入数据帧:

     RevID     Date      Revenue
     1         1/2/2015  24000.00
     2         1/2/2015  25000.00
     1         2/2/2015  10000.00
     4         3/2/2015  94000.00

我的问题是,考虑到有时性能DF中会有一个逗号分隔的值(如数组),需要从revenue DF中同时找到两个对应的revenue行和日期,如何对这两行执行合并。你知道吗

例如,我将如何处理这个问题,以便最终表格显示:

     RevID         Date       PartnerName        Performance        Revenue
     1,2           1/2/2015   Johndoe            0.02               49000.00
     1             2/2/2015   Johndoe            0.12               10000.00
     4             3/2/2015   Johndoe            0.10               94000.00

请注意,第一行中的收入已与RevID 1和2的值相加。 在这一点上,任何帮助都将是伟大的!你知道吗


Tags: 数据脚本idpandasdfdateperformance性能
1条回答
网友
1楼 · 发布于 2024-03-29 13:33:56

我只要复制这些数据,逗号的问题就消失了:

In [11]: res = pd.concat([df.iloc[i] for val, i in g.groups.items() for v in val.split(',')], ignore_index=True)

In [12]: res['RevID'] = sum([val.split(',') for val in g.groups], [])

并确保revid是数字而不是字符串:

In [13]: res['RevID'] = res['RevID'].convert_objects(convert_numeric=True)

In [14]: res
Out[14]:
  RevID      Date PartnerName  Performance  Revenue
0     1  2/2/2015     Johndoe         0.12        0
1     1  1/2/2015     Johndoe         0.02        0
2     2  1/2/2015     Johndoe         0.02        0
3     4  3/2/2015     Johndoe         0.10        0

这样你就可以合并了,你基本上做到了:

In [21]: res.merge(df2, on=['RevID', 'Date'])
Out[21]:
   RevID      Date PartnerName  Performance  Revenue_x  Revenue_y
0      1  2/2/2015     Johndoe         0.12          0      10000
1      1  1/2/2015     Johndoe         0.02          0      24000
2      2  1/2/2015     Johndoe         0.02          0      25000
3      4  3/2/2015     Johndoe         0.10          0      94000

注意:您可能希望在合并之前删除0 Revenue列(这样就不需要指定on)。你知道吗

如果你想引用一个原始的ID(一些独特的东西),那么你可以将它分组,然后将收入相加,得到你想要的帧。。。

相关问题 更多 >