如何合并月份和年份列以获取单个mm-yyyy列? [英] How to merge month and year columns to get single mm-yyyy column?

查看:157
本文介绍了如何合并月份和年份列以获取单个mm-yyyy列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的df:

Sr.  lwd_month lwd_year
1     3        2015
2     6        2018
3.    9        2017
4.    NaN      NaN
5.    5        2015

如何合并这两列以获取如下所示的数据框?

How can I merge this two columns to get dataframe like below?:

Sr.  lwd_month   lwd_Year   MonthYear
1     3          2015    03-2015
2     6          2018     06-2018
3.    9          2017     09-2017
4.    NaN        NaN      NaT
5.    5          2015     05-2015
6.    3          NaN      NaT

谢谢

推荐答案

首先需要使用小写 year month 和熊猫版本 0.18.1 +

First need columns names with lowercase year and month and pandas version 0.18.1+.

然后使用 to_datetime 用于转换通过多列 strftime 用于字符串:

Then use to_datetime for convert by multiple columns with strftime for strings:

df['MonthYear']=pd.to_datetime(df.assign(day=1)[['year','month','day']]).dt.strftime('%m-%Y')
print (df)
   Sr.  month    year MonthYear
0  1.0    3.0  2015.0   03-2015
1  2.0    6.0  2018.0   06-2018
2  3.0    9.0  2017.0   09-2017
3  4.0    NaN     NaN       NaT
4  5.0    5.0  2015.0   05-2015

print (type(df.loc[0, 'MonthYear']))
<class 'str'>

与月度类似使用 to_period

Similar for month period use to_period:

df['MonthYear'] = pd.to_datetime(df.assign(day=1)[['year','month','day']]).dt.to_period('m')
print (df)
   Sr.  month    year MonthYear
0  1.0    3.0  2015.0   2015-03
1  2.0    6.0  2018.0   2018-06
2  3.0    9.0  2017.0   2017-09
3  4.0    NaN     NaN       NaT
4  5.0    5.0  2015.0   2015-05

print (type(df.loc[0, 'MonthYear']))
<class 'pandas._libs.tslibs.period.Period'>

这篇关于如何合并月份和年份列以获取单个mm-yyyy列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆