Python Pandas 连接或调整数据以添加两个具有重复值的新列

标签 python pandas

好的。我不知道如何实际问这个问题,但这里是。我有一个像这样的数据框。

import pandas as pd

d = {'Product' : ['Product_A','Product_A', 'Product_B', 'Product_B'],'Country' : ["DE", "DE", "DE","DE"],'Billed_Week' : ['201652', '201701', '201652', '201701'],'Billings' : [1116, 9030, 7476, 2859]}
df = pd.DataFrame(d)

sequence = ['Product','Country','Billed_Week','Billings']
df = df.reindex(columns=sequence)

输出:

    Product   Country  Billed_Week  Billings
0  Product_A      DE     201652      1116
1  Product_A      DE     201701      9030
2  Product_B      DE     201652      7476
3  Product_B      DE     201701      2859

我需要再添加两列“Billed_Week_New”和“Billings_New”,其中基于整个第一个数据帧的分组以重复格式添加值。因此,对于第一个数据帧的第一条记录,我需要扩展整个分组中的周数。我将只显示所需的输出。

所需输出:

Product    Country  Billed_Week  Billings   Billed_Week_New   Billings_New
Product_A   DE       201652       1116        201652             1116
Product_A   DE       201652       1116        201701             9030
Product_A   DE       201701       9030        201652             1116
Product_A   DE       201701       9030        201701             9030
Product_B   DE       201652       7476        201652             7476
Product_B   DE       201652       7476        201701             2859
Product_B   DE       201701       2859        201652             7476
Product_B   DE       201701       2859        201701             2859

最佳答案

考虑交叉连接,在列之间返回笛卡尔积(此处相同键上的集合之间的所有可能组合是产品国家/地区):

mdf = df.merge(df, on=['Product','Country']).\
      rename(columns = {'Billed_Week_x': 'Billed_Week',
                        'Billings_x': 'Billings',
                        'Billed_Week_x':'Billed_Week_New',
                        'Billings_y':'Billings_New'})
print(mdf)

#      Product Country Billed_Week  Billings Billed_Week_New  Billings_New
# 0  Product_A      DE      201652      1116          201652          1116
# 1  Product_A      DE      201652      1116          201701          9030
# 2  Product_A      DE      201701      9030          201652          1116
# 3  Product_A      DE      201701      9030          201701          9030
# 4  Product_B      DE      201652      7476          201652          7476
# 5  Product_B      DE      201652      7476          201701          2859
# 6  Product_B      DE      201701      2859          201652          7476
# 7  Product_B      DE      201701      2859          201701          2859

关于Python Pandas 连接或调整数据以添加两个具有重复值的新列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43106534/

相关文章:

python - 如何使用 Python 循环遍历列中的行并对其进行计数?

java - 使用 Jython 和 Swing 处理事件

python - MySQL:在重复键上插入不同值时设置 "diff"位?

python - 最后 2 秒的滚动总和

python - 如何替换 pandas.Dataframe 中的部分字符串?

python - 如何使用 itertools 提取 groupby 值?

python - 如何在python中初始化一个二维字符串DataFrame数组

Python 打印到文件不工作

python - Pandas 更改列日期格式

python - 使用 python 弹出数据框单元格中的第一个元素