pandas列名的修改

生成一个 dataframe

1
2
3
4
5
6
7
8
9
10
import pandas as pd
import numpy as np

df = pd.DataFrame(np.random.rand(2, 4))
print(df)

#
# 0 1 2 3
# 0 0.714730 0.566612 0.764352 0.728862
# 1 0.823414 0.662657 0.800281 0.711702

定义列名

1
2
3
4
5
6
7
8
df.columns = ['beijing', 'shanghai', 'guangzhou', 'shenzhou']
print(df)

#
# beijing shanghai guangzhou shenzhou
# 0 0.714730 0.566612 0.764352 0.728862
# 1 0.823414 0.662657 0.800281 0.711702

重命名列

1
2
3
4
5
6
7
df.rename({'beijing':'A', 'shanghai':'B', 'guangzhou':'C', 'shenzhou':'D'}, axis='columns', inplace=True)
print(df)

#
# A B C D
# 0 0.714730 0.566612 0.764352 0.728862
# 1 0.823414 0.662657 0.800281 0.711702

重命名列2

1
2
3
4
5
6
7
df.rename(columns={'A':'A_1', 'B':'B_1', 'C':'C_1', 'D':'D_1'}, inplace=True)
print(df)

#
# A_1 B_1 C_1 D_1
# 0 0.714730 0.566612 0.764352 0.728862
# 1 0.823414 0.662657 0.800281 0.711702

替换特定的字符或前缀/后缀

1
2
3
4
5
6
7
df.columns = df.columns.str.replace('_', '')
print(df)

#
# A1 B1 C1 D1
# 0 0.714730 0.566612 0.764352 0.728862
# 1 0.823414 0.662657 0.800281 0.711702