直接替换df.columns和df.index
不可以对df.columns和df.index中某个单独的元素操作,需要整体替换
df = pd.DataFrame(np.arange(12).reshape(3,4))
df
>>> 0 1 2 3
0 0 1 2 3
1 4 5 6 7
2 8 9 10 11
# 使用df.columns替换所有列名
df.columns=[2,3,4,5]
df
>>> 2 3 4 5
0 0 1 2 3
1 4 5 6 7
2 8 9 10 11
# 使用df.index替换所有行index
df.index = [2,3,4]
df
>>> 2 3 4 5
2 0 1 2 3
3 4 5 6 7
4 8 9 10 11
使用df.rename()
df.rename(
mapper=None,
index=None,
columns=None,
axis=None,
copy=True,
inplace=False,
level=None,
errors='ignore',
)
mapper+axis 或者 columns替换列名
使用mapper+axis时,axis=1
或者axis='columns'
df = pd.DataFrame(np.arange(12).reshape(3,4))
df
>>> 0 1 2 3
0 0 1 2 3
1 4 5 6 7
2 8 9 10 11
# mapper+axis
df.rename({0:'col0'}, axis=1)
>>>col0 1 2 3
0 0 1 2 3
1 4 5 6 7
2 8 9 10 11
df.rename({0:'col0'}, axis='columns')
>>>col0 1 2 3
0 0 1 2 3
1 4 5 6 7
2 8 9 10 11
# columns
df.rename(columns={0:'col0', 2:'col2'})
>>>col0 1 col2 3
0 0 1 2 3
1 4 5 6 7
2 8 9 10 11
mapper+axis 或者 index替换行Index名
使用mapper+axis时,axis=0
或者axis='rows'
或者axis='index'
df = pd.DataFrame(np.arange(12).reshape(3,4))
df
>>> 0 1 2 3
0 0 1 2 3
1 4 5 6 7
2 8 9 10 11
# mapper+axis
df.rename({0:'row0'}, axis=0)
>>> 0 1 2 3
row0 0 1 2 3
1 4 5 6 7
2 8 9 10 11
df.rename({0:'row1'}, axis='rows')
>>> 0 1 2 3
row1 0 1 2 3
1 4 5 6 7
2 8 9 10 11
# index
df.rename(index={0:'row0', 2:'row2'})
>>> 0 1 2 3
row0 0 1 2 3
1 4 5 6 7
row2 8 9 10 11