[英]Column Header rename loop in Python
Looking for a solution using python to rename the column headers in the below example DataFrame starting at GStart:GS1
.寻找使用 python 重命名以下示例中的列标题的解决方案 DataFrame 从
GStart:GS1
开始。 I need to rename the 2 columns adjacent to the already named column and repeat this for the whole data frame.我需要重命名与已命名列相邻的 2 列,并对整个数据框重复此操作。
For example, find the next named, rename the next two columns and repeat.例如,找到下一个命名的,重命名接下来的两列并重复。 I can complete this using the rename pandas method but is there a way to create a loop as the named column headers will not always be the same.
我可以使用重命名 pandas 方法完成此操作,但是有没有办法创建一个循环,因为命名的列标题并不总是相同的。
Example DataFrame:示例 DataFrame:
You can try below code to rename the column names.您可以尝试下面的代码来重命名列名。 I assume that there is always a set of 3 columns to rename from 'GStart:GS1' onwards.
我假设总是有一组 3 列要从“GStart:GS1”开始重命名。
#define the original list of column names
df_columns = list(df.columns)
#extract the relevant column names to rename
col_list = df_columns[ df_columns.index('GStart:GS1') : ]
#using this loop with step=3 to look for the starting column name, and append column names with 'A', 'B', 'C' for each set of 3 columns
for i in range(0, len(col_list), 3):
name = col_list[i]
col_list[i] = name+'A'
col_list[i+1] = name+'B'
col_list[i+2] = name+'C'
#replace with new column names
df_columns[ df_columns.index('GStart:GS1') : ] = col_list
df.columns = df_columns
Output: Output:
['NaN',
'NaN',
'GStart:GS1A',
'GStart:GS1B',
'GStart:GS1C',
'GStart:GS2A',
'GStart:GS2B',
'GStart:GS2C',
'GHIP_Test:HIP1A',
'GHIP_Test:HIP1B',
'GHIP_Test:HIP1C',
'GHIP_Test:HIP2A',
'GHIP_Test:HIP2B',
'GHIP_Test:HIP2C',
'GHIP_Test:HIP3A',
'GHIP_Test:HIP3B',
'GHIP_Test:HIP3C']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.