如何对一列使用数据透视/分组,而对其他列进行连接?

时间:2019-03-27 17:26:16

标签: python pandas dataframe pivot

我想基于一个列(月)创建透视表/表摘要,并隐瞒其他列。这里的关键是我不知道期望的列名称(月份和计算的),因此info1和info2的列名称可能会更改,因此我无法对其进行硬编码,但是我可以对Month和Calculated进行硬编码。输入为:input

我已经尝试过数据透视表,但它没有显示所有列,也没有做我需要做的事情。

import pandas as pd
from collections import OrderedDict

d = {'Month': [1, 2, 2],
     'Calculated': [300, 400, 460],
     'info1': ["my info", "i really need the tech", "some more info"], 
     'info2': ["sales are good", "lets do more tech", "my third line"]}

df = pd.DataFrame(data=d)

df.to_csv("myfile.csv")


df1 = df.pivot_table(index = ['Month'], aggfunc=lambda x: ' '.join(x)).reset_index()

df1.to_csv("myfile1.csv")

我希望所有列都在那儿,按月分组并连接其他列。预期输出为expected output

请不要担心csv部分,我这样做是为了截图此问题。

解决方案:

df.astype(str).pivot_table(index = ['Month'], aggfunc=lambda x: '\n'.join(x)).reset_index().reindex(columns=df.columns)

1 个答案:

答案 0 :(得分:1)

您首先需要使用astype(str)

更改数据类型。
df.astype(str).pivot_table(index = ['Month'], aggfunc=lambda x: '\n'.join(x)).reset_index()