简体   繁体   English

Python:如何用元组中的列名重命名 dataframe?

[英]Python: how to rename dataframe with column names in tuple?

I have the dataframe below我下面有 dataframe

   Col1/sum/mean     Col2/sum/mean   Col3/sum/mean
A      1                   2                3
B      4                   5                6
C      7                   8                9

I find it annoying to access the column by doing df[('Col1','sum','mean')] everytime, is there a way to remove the sum and mean levels?我发现每次都通过df[('Col1','sum','mean')]访问该列很烦人,有没有办法删除summean水平? Or rename it?还是重命名?

If there are tuples select first value of tuple:如果有元组 select 元组的第一个值:

df.columns = [x[0] for x in df.columns]

If no tuples use str.split with selecting first value:如果没有元组使用str.split选择第一个值:

df.columns = df.columns.str.split('/').str[0]
print (df)
   Col1  Col2  Col3
A     1     2     3
B     4     5     6
C     7     8     9

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

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