[英]reset_index() to original column indices after pandas groupby()?
I generate a grouped dataframe df = df.groupby(['X','Y']).max()
which I then want to write (to csv, without indexes). 我生成一个分组的数据帧
df = df.groupby(['X','Y']).max()
然后我想写(到csv,没有索引)。 So I need to convert 'X' and 'Y' back to regular columns; 所以我需要将'X'和'Y'转换回常规列; I tried using
reset_index()
, but the order of columns was wrong. 我尝试使用
reset_index()
,但列的顺序是错误的。
How to restore columns 'X' and 'Y' to their exact original column position? 如何将列'X'和'Y'恢复到其确切的原始列位置?
Is the solution: 是解决方案:
df.reset_index(level=0, inplace=True)
and then find a way to change the order of the columns? 然后找到一种方法来改变列的顺序?
(I also found this approach, for multiindex ) (我也找到了这种方法,用于多索引 )
This solution keeps the columns as-is and doesn't create indexes, after grouping, hence we don't need reset_index()
and column reordering at the end: 在分组之后,此解决方案保持列不按原样并且不创建索引,因此我们最后不需要
reset_index()
和列重新排序:
df.groupby(['X','Y'],as_index=False).max()
(After testing a lot of different methods, the simplest one was the best solution (as always) and the one which eluded me the longest. Thanks to @maxymoo for pointing it out.) (在测试了很多不同的方法之后,最简单的方法是最好的解决方案(一如既往)和最长的方法。感谢@maxymoo指出它。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.