[英]Pandas DataFrame.reset_index for columns
Is there a reset_index
equivalent for the column headings?列标题是否有等效的
reset_index
? In other words, if the column names are an MultiIndex
, how would I drop one of the levels?换句话说,如果列名是
MultiIndex
,我将如何删除其中一个级别?
Answer to the second question:回答第二个问题:
df.columns = df.columns.droplevel(level)
First question is as @AndyHayden points out not that straight forward.第一个问题是@AndyHayden 指出的不是那么直接。 It only would make sense if your columns names are of the same type as your column values.
只有当您的列名称与您的列值属于相同类型时才有意义。
Here's a really dumb way to turn your columns into tuples instead:这是将列转换为元组的一种非常愚蠢的方法:
df.columns = list(df.columns)
You can build on that to get whatever you want, for example if you had a 2 level MultiIndex
, to remove the outermost level, you could just do:您可以在此基础上获得任何您想要的东西,例如,如果您有一个 2 级
MultiIndex
,要删除最外层,您可以这样做:
df.columns = [col[1] for col in df.columns]
You can't do fancy indexing over the iteration because it's generating tuples, but you can do things like:您不能对迭代进行花哨的索引,因为它会生成元组,但您可以执行以下操作:
df.columns = MultiIndex.from_tuples([col[1:] for col in df.columns]
So you have some options there.所以你有一些选择。
转置 df,重置索引,然后再次转置。
df.T.reset_index().T
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.