【问题标题】:how to combine the data in dataframe如何组合数据框中的数据
【发布时间】:2018-12-11 11:57:44
【问题描述】:

我正在处理在 csv 文件中有记录的数据集:

 C_id  C_Name        S_Name                Phone
    97  [Bedsheet]     Shree Collection     77422222
    97  [Bedsheet]    Shree Collection      77422222
    105 [Jeans]       Shree Collection      77422222
    61  [Kurti]       F Fashion             9040645
    95  [Lehenga]     Shree Collection      77422222
    61  [Kurti]        F Fashion        9040645
    73  [Cotton Kurti] F Fashion        9040645
    117 [Earring]              Banti        90406459

我想将数据显示为:

C_id       C_Name                    S_Name              Phone
97,105,95   Bedsheet,Jeans,Lehenga   Shree Collection    77422222
61,73       Kurti,Cotton Kurti       F Fashion           9040645
117          Earring                 Banti               90406459

如何做到这一点

【问题讨论】:

  • 请展示您的尝试。我想,你说的是 Pandas DataFrames?

标签: python python-2.7 pandas dataframe pandas-groupby


【解决方案1】:

您可以将groupbyagg 和几个str.join 函数一起使用。需要特别注意的部位:

  • 对于C_id,由于str.join 需要字符串,您需要将int 转换为str
  • 对于C_Name,您有一系列列表。 itertools.chain 是将这些列表扁平化为非嵌套迭代的有效方法。

这是一个工作示例:

from itertools import chain

agg_funcs = {'C_id': lambda x: ','.join(map(str, x)),
             'C_Name': lambda x: ','.join(chain.from_iterable(x))}

res = df.groupby(['S_Name', 'Phone']).agg(agg_funcs).reset_index()

print(res)

             S_Name     Phone          C_id                           C_Name
0             Banti  90406459           117                          Earring
1         F Fashion   9040645      61,61,73         Kurti,Kurti,Cotton Kurti
2  Shree Collection  77422222  97,97,105,95  Bedsheet,Bedsheet,Jeans,Lehenga

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-30
    • 1970-01-01
    • 2022-08-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多