KOAK.rename(columns = lambda x : 'KOAK-' + x, inplace=True)
以上代码使我能够在数据框的所有列标题前添加“KOAK”,但我只想将KOAK前缀添加到第4-38列。我该如何做?
KOAK.rename(columns = lambda x : 'KOAK-' + x, inplace=True)
以上代码使我能够在数据框的所有列标题前添加“KOAK”,但我只想将KOAK前缀添加到第4-38列。我该如何做?
列
:KOAK.columns = ['KOAK-' + x if 4 <= i <= 38 else x for i, x in enumerate(KOAK.columns, 1)]
例子:
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)
输出:
A KOAK-B KOAK-C KOAK-D E F G
0 12 12 12 12 12 12 12
x
转换为 str
吗? - EdChumx in KOAK.columns
зҡ„иҝ”еӣһеҖјжҳҜеӯ—з¬ҰдёІгҖӮ - Mike Müllerdf = pd.DataFrame(columns=[0,1,2,3,4])
然后 df.columns.tolist()
返回:[0, 1, 2, 3, 4]
。 - EdChumlambda
函数中执行'KOAK-' + x
。 - Mike Müllerrename
来创建一个字典: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: []
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)