我的数据集如下:
Year Month Partisan Conflict
0 1981 January 68.944808
1 1981 February 64.907109
2 1981 March 79.058476
3 1981 April 69.324041
4 1981 May 88.194466
数据是从excel文件导入的。
我想知道如何以类似这样的格式加入年份和月份的列:
1981-01
1981-02
...
我检查了它们的格式。
type(df.iloc[0]['Month'])
str
type(df.iloc[0]['Year'])
numpy.int64
但是将它们加在一起是我没有弄清楚的问题。谁能帮我?谢谢!
答案 0 :(得分:3)
首先将Year
和Month
列连接起来,然后使用pd.to_datetime
将此连接的列转换为熊猫日期时间序列,然后使用Series.dt.strftime
将该日期时间序列转换为所需格式:
df['Date'] = pd.to_datetime(
df['Year'].astype(str) + df['Month'], format='%Y%B').dt.strftime('%Y-%m')
或者,也可以使用mappings
字典通过Series.map
映射Month
列:
mappings = {'January': '01', 'February': '02', 'March': '03', 'April': '04', 'May': '05', 'June': '06',
'July': '07', 'August': '08', 'September': '09', 'Octomber': '10', 'November': '11', 'December': '12'}
df['Date'] = df['Year'].astype(str) + '-' + df['Month'].map(mappings)
# print(df)
Year Month Partisan Conflict Date
0 1981 January 68.944808 1981-01
1 1981 February 64.907109 1981-02
2 1981 March 79.058476 1981-03
3 1981 April 69.324041 1981-04
4 1981 May 88.194466 1981-05
答案 1 :(得分:0)
您可以尝试使用以下代码吗?
Dates = {'Month': ['Jun','Jul','Aug','Sep','Oct'],
'Year': [2016,2017,2018,2019,2020]}
df = DataFrame(Dates, columns= ['Month','Year'])
df1 = df['Month'].map(str) + '-' + df['Year'].map(str)
print (df1)
Note I just gave an example to resolve the issue.