我正在尝试使用Python将数据帧中的多个列重命名为特定日期。
目前,列如下: 2016-04、2016-05、2016-06....
我希望这些列显示为: April2016,May2016,June2016...
大约有40列。我猜for循环是最有效的方法,但是我对Python比较陌生,不确定如何正确地连接列名。
发布于 2019-06-18 03:20:49
您可以使用循环或理解以及月份字典来拆分、重新排序和替换字符串列名称
#in your case this would be cols=df.columns
cols=['2016-04', '2016-05', '2016-06']
rpl={'04':'April','05':'May','06':'June'}
cols=[\
''.join(\
[rpl[i.split('-')[1]],
i.split('-')[0]]) \
for i in cols]
cols
['April2016', 'May2016', 'June2016']
#then you would assign it back with df.columns = cols发布于 2019-06-18 03:20:38
你没有分享你的数据框,所以我使用了基本的数据框来解释如何获得月份的日期。我假设你的数据框如下:
d = {'dates': ['2016-04', '2016-05','2016-06']} #just 3 of them所以所有的代码:
import datetime
import pandas as pd
d = {'dates': ['2016-04', '2016-05','2016-06']}
df = pd.DataFrame(d)
for index, row in df.iterrows():
get_date= row['dates'].split('-')
get_month = get_date[1]
month = datetime.date(1900, int(get_month), 1).strftime('%B')
print (month+get_date[0])输出:
2016April
2016May
2016Junehttps://stackoverflow.com/questions/56637456
复制相似问题