[英]How to change the column names of a Pandas DataFrame?
I have a Pandas DataFrame with n columns, don't know how many columns will be there.我有一个 Pandas DataFrame 有 n 列,不知道会有多少列。
df = index task_1 task_2 ......
0 dummy_1 dummy_2 ....
1 dum_1 dum_2 ...
I want to change the names of the column from task_1 to Label_1 and so on.The out put needs to be我想将列的名称从 task_1 更改为 Label_1 等等。输出需要是
df = index Label_1 Label_2 ......
0 dummy_1 dummy_2 ....
1 dum_1 dum_2 ...
You still need to find out how many columns are there您仍然需要找出有多少列
You can do that by你可以这样做
len(df.columns)
and you can change the names in sequence by iterating through a loop for eg"并且您可以通过迭代循环来按顺序更改名称,例如“
df.columns=["Label_"+str(i) for i in range(1, 17)]
You can iterate through all columns and replace "task"
with "Label"
like this.您可以遍历所有列并将
"task"
替换为"Label"
,如下所示。 And this only applies to columns that has "task"
in their name and others remains unchanged:这仅适用于名称中包含
"task"
的列,其他列保持不变:
df.columns = [name.replace('task', 'Label') for name in df.columns]
Use the DataFrame.rename
method, passing a dictionary to the columns
argument where the keys are the old column names and the values are the new column names:使用
DataFrame.rename
方法,将字典传递给columns
参数,其中键是旧列名,值是新列名:
df.rename(columns={"task_1": "Label_1"}, inplace=True)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.