程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

pandas DataFrame中修改列名和行index

編輯:Python

直接替換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

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved