简体   繁体   English

如何通过将行值附加到 Pandas 中的列名来重命名列?

[英]How to rename columns by appending the row value to the column name in Pandas?

I have a dataframe as such:我有一个 dataframe 这样的:

**A**       **B**           **C**             **Name**
Hello       No              Why               -
2           5               303               Sir

And I want to rename the columns by appending the row value to the column name:我想通过将行值附加到列名来重命名列:

A_Hello      B_No      C_Why      Name    
2            5         303        Sir

(That row will be removed after I change the column names) (更改列名后,该行将被删除)

Here is a more general solution that would apply to a much larger dataframe without having to manually rename the columns:这是一个更通用的解决方案,适用于更大的 dataframe 而无需手动重命名列:

df.columns = [col.replace('*','')+ '_' +df.iloc[0,idx] for idx, col in enumerate(df.columns)]
df = df[1:]

print(df)
#output:
  A_Hello B_No C_Why Name_-
1       2    5   303    Sir

One more way of doing it.另一种方法。 Nothing manul needed & there is no _ after 'Name' for the last column name either.不需要任何手动操作,并且在最后一列名称的“名称”之后也没有_

name_list = []
for a,b in zip ([item.replace('*','') for item in df.columns.to_list()],df.iloc[0,:].to_list()):
    if b.isalpha():
        name_list.append(f'{a}_{b}')
    else:
        name_list.append(a)
df.rename(columns={x:y for x,y in zip(df.columns,name_list)}, inplace = True)
df = df[1:]

Output Output

A_Hello     B_No    C_Why   Name
2             5     303     Sir

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

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