Python Pandas 重命名轴索引的多种实现方式
本文介绍在Python中使用Pandas库重命名DataFrame轴索引的两种主要方法。通过index.map()可直接修改原数据,而rename()函数支持传入函数或字典进行灵活映射,并可选择是否原地修改。
具体实现代码如下所示:
import numpy as np
from pandas import Series, DataFrame
###重命名轴索引
data = DataFrame(np.arange(12).reshape((3, 4)),
index=['Ohio', 'Colorado', 'New York'],
columns=['one', 'two', 'three', 'four'])
print( data.index.map(str.upper) ) #['OHIO' 'COLORADO' 'NEW YORK']
data.index = data.index.map(str.upper)
print( data )
'''
one two three four
OHIO 0 1 2 3
COLORADO 4 5 6 7
NEW YORK 8 9 10 11
'''
data_2 = data.rename(index=str.title, columns=str.upper)
print( data_2 )
'''
ONE TWO THREE FOUR
Ohio 0 1 2 3
Colorado 4 5 6 7
New York 8 9 10 11
'''
data_3 = data.rename(index={'OHIO': 'INDIANA'},
columns={'three': 'peekaboo'})
print( data_3 )
'''
one two peekaboo four
INDIANA 0 1 2 3
COLORADO 4 5 6 7
NEW YORK 8 9 10 11
'''
# 总是返回DataFrame的引用
_ = data.rename(index={'OHIO': 'INDIANA'}, inplace=True)
print( _ ) # None
上述内容即为Python中重命名轴索引的完整操作方法,旨在为读者提供实用的参考。如果您觉得本文对您有帮助,欢迎继续支持本站获取更多技术分享。
本站声明
本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。













