简体   繁体   English

熊猫在聚合后选择要保存的列

[英]pandas select columns to save after aggregation

I'm reading data and calculate mean for groups, and then save the data to other file. 我正在读取数据并计算组的均值,然后将数据保存到其他文件中。 The problem is that I want to select only some of the columns to write to that file, currently it gives me error, so I have to save all to the file, then reopen, choose columns and write again. 问题是我只想选择一些列来写入该文件,当前它给了我错误,所以我必须将所有内容保存到文件中,然后重新打开,选择列并再次写入。

This code doesn't work: 该代码不起作用:

df = pd.read_csv("./file.csv")
grouped = df.groupby(['Condition','ID','BeginEnd'])
agg = grouped.mean()
agg = agg[['Condition','ID','BeginEnd3','KnowledgeScore']]
agg.to_csv('file2.csv')

I have to do this: 我必须这样做:

df = pd.read_csv("./file.csv")
grouped = df.groupby(['Condition','ID','BeginEnd'])
agg = grouped.mean()
agg.to_csv('file2.csv')
df3 = pd.read_csv('file2.csv')
df3 = df3[['Condition','ID','BeginEnd3','KnowledgeScore']]
df3.to_csv('file2.csv')

You didn't post either the code you tried which didn't work or the full traceback of the error message, so we're left having to guess what the issue is. 您没有发布尝试的代码无法正常工作,也没有发布错误消息的完整回溯信息,因此我们不得不猜测问题出在哪里。 ("currently it gives me error" isn't very useful.) I'm assuming you tried something like (“当前它给我带来错误”不是很有用。)我假设您尝试了类似的方法

agg = agg[['Condition','ID','BeginEnd3','KnowledgeScore']]

That wouldn't have worked because after grouping, the columns that you grouped on become parts of the index ( print agg.index to see) and not columns ( print agg.columns ). 那是行不通的,因为在分组之后,您分组的列将成为索引( print agg.index以查看)而不是列( print agg.columns )的一部分。 You can promote them to columns again using reset_index : 您可以使用reset_index它们再次提升为列:

agg = grouped.mean().reset_index()

Example: 例:

>>> df
   A  B  C
0  0  2  6
1  0  2  7
2  1  3  8
3  1  4  9
>>> grouped = df.groupby(["A", "B"])
>>> agg = grouped.mean()
>>> agg
       C
A B     
0 2  6.5
1 3  8.0
  4  9.0
>>> agg = agg.reset_index()
>>> agg
   A  B    C
0  0  2  6.5
1  1  3  8.0
2  1  4  9.0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM