我想基于一个列(月)创建透视表/表摘要,并隐瞒其他列。这里的关键是我不知道期望的列名称(月份和计算的),因此info1和info2的列名称可能会更改,因此我无法对其进行硬编码,但是我可以对Month和Calculated进行硬编码。输入为:
我已经尝试过数据透视表,但它没有显示所有列,也没有做我需要做的事情。
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")
请不要担心csv部分,我这样做是为了截图此问题。
解决方案:
df.astype(str).pivot_table(index = ['Month'], aggfunc=lambda x: '\n'.join(x)).reset_index().reindex(columns=df.columns)
答案 0 :(得分:1)
您首先需要使用astype(str)
df.astype(str).pivot_table(index = ['Month'], aggfunc=lambda x: '\n'.join(x)).reset_index()