简体   繁体   English

如何在Python(Pandas)中重命名特定范围的列

[英]How to rename a specific range of columns in Python (Pandas)

 KOAK.rename(columns = lambda x : 'KOAK-' + x, inplace=True)

The above code allows me to add 'KOAK' in front of all column headers in my data frame but I only want to add the KOAK prefix to column numbers 4-38. 上面的代码允许我在数据框中所有列标题的前面添加“ KOAK”,但是我只想将KOAK前缀添加到第4-38列。 How would I go about doing this? 我将如何去做呢?

You can assign to columns : 您可以分配给columns

KOAK.columns = ['KOAK-' + x if 4 <= i <= 38 else x for i, x in enumerate(KOAK.columns, 1)]

Example: 例:

KOAK = pd.DataFrame(dict.fromkeys('ABCDEFG', [12]))
KOAK.columns = ['KOAK-' + x if 2 <= i <= 4 else x 
                for i, x in enumerate(KOAK.columns, 1)]
print(KOAK)

Prints: 打印:

    A  KOAK-B  KOAK-C  KOAK-D   E   F   G
0  12      12      12      12  12  12  12

You can create a dict by zipping the column ordinal range with a list comprehension and passing this to rename : 您可以通过使用列表推导压缩列序范围并将其传递给rename来创建字典:

In [2]:
df = pd.DataFrame(columns=list('abcdefg'))
df

Out[2]:
Empty DataFrame
Columns: [a, b, c, d, e, f, g]
Index: []

In [3]:
new_cols = dict(zip(df.columns[2:5], ['KOAK-' + x for x in df.columns[2:5]]))
new_cols

Out[3]:
{'c': 'KOAK-c', 'd': 'KOAK-d', 'e': 'KOAK-e'}

In [6]:    
df.rename(columns= new_cols, inplace=True)
df

Out[6]:
Empty DataFrame
Columns: [a, b, KOAK-c, KOAK-d, KOAK-e, f, g]
Index: []

so in your care the following should work: 因此,在您的护理下,以下方法应该起作用:

new_cols = dict(zip(df.columns[3:47], ['KOAK-' + str(x) for x in df.columns[3:47]]))
df.rename(columns= new_cols, inplace=True)

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

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