pandas中的rename_axis用法

Series.rename_axis(mapper=None, index=None, columns=None, axis=None, copy=True, inplace=False)

用index或者column来设置axis的名称

具体看例子:

id_ohlc = 'AShareEODPrices'
instrument = ['000002.SZ']
start_date = '2017-01-01'
end_date = '2018-01-01'
target_fields=['open', 'high', 'low', 'close', 'volume', 'amount', 'adjust_factor']
origin_fields=['s_dq_adjopen','s_dq_adjhigh','s_dq_adjlow','s_dq_adjclose','s_dq_volume','s_dq_admount','s_dq_adjfactor']
df = DataSource(id_ohlc).read(instrument, start_date=start_date, end_date=end_date,
                              fields=origin_fields).set_index('date')
df.rename_axis({x:y for x,y in zip(origin_fields,target_fields)},axis=1, inplace=True)  # ***
df.head(3)

没有***句运行结果为:

有***句运行结果为:

可以看到,其实就是把column名换了下而已,python中的 zip() 函数用于将可迭代的对象作为参数,将对象中对应的元素打包成一个个元组,然后返回由这些元组组成的列表。程序中此处相当于 x 和 y 互换,而 (x, y) 就是origin_fields和target_fields组成的元组,具体如下:

target_fields=['open', 'high', 'low', 'close', 'volume', 'amount', 'adjust_factor']
origin_fields=['s_dq_adjopen','s_dq_adjhigh','s_dq_adjlow','s_dq_adjclose','s_dq_volume','s_dq_admount','s_dq_adjfactor']
for x, y in zip(target_fields, origin_fields):
    print(x, y)

原文地址:https://www.cnblogs.com/xiaodongsuibi/p/10870977.html