Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/286.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何对一列使用pivot/groupby并连接其他列?_Python_Pandas_Dataframe_Pivot - Fatal编程技术网

Python 如何对一列使用pivot/groupby并连接其他列?

Python 如何对一列使用pivot/groupby并连接其他列?,python,pandas,dataframe,pivot,Python,Pandas,Dataframe,Pivot,我想根据一列(月)和其他列做一个数据透视/表格摘要。这里的关键是我不知道expect(Month和Calculated)的列名,因此info1和info2的列名可能会更改,因此我无法硬编码它们,但我可以硬编码Month和Calculated。输入为: 我已经尝试了pivot表,但它没有显示所有列,也没有执行我需要的操作 import pandas as pd from collections import OrderedDict d = {'Month': [1, 2, 2], 'C

我想根据一列(月)和其他列做一个数据透视/表格摘要。这里的关键是我不知道expect(Month和Calculated)的列名,因此info1和info2的列名可能会更改,因此我无法硬编码它们,但我可以硬编码Month和Calculated。输入为:

我已经尝试了pivot表,但它没有显示所有列,也没有执行我需要的操作

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)

您需要首先使用
astype(str)


它不会产生预期的输出Hanks很多!这很有帮助。一个快速的后续问题,它改变了列的顺序。如果我想要一个月的时间,我能做些什么。(它将计算出的数据发送到最后)@shaucha
df.astype(str).pivot\u table(index=['Month'],aggfunc=lambda x:''.join(x)).reset\u index().reindex(columns=df.columns)
add reindex在最后,它将确保列的顺序与原始列相同df@user32185“你什么意思?”文本,谢谢!效果很好,我刚刚添加了“\n”,效果很好。
df.astype(str).pivot_table(index = ['Month'], aggfunc=lambda x: '\n'.join(x)).reset_index()