![](/img/trans.png)
[英]How to split column of type interval[int64,right) onto two columns in Pandas
[英]Split int64 Pandas column in two
我已经获得了一个数据集,其日期为整数,使用20119年5月的格式52019.我已将它放入Pandas DataFrame中,我需要将该日期格式提取到月份列和年份列中,但我可以要弄清楚如何为int64数据类型执行此操作或如何处理两个数字月份。 所以我想采取类似的方式
ID Date
1 22019
2 32019
3 52019
5 102019
并使它成为
ID Month Year
1 2 2019
2 3 2019
3 5 2019
5 10 2019
我该怎么办?
divmod
df['Month'], df['Year'] = np.divmod(df.Date, 10000)
df
ID Date Month Year
0 1 22019 2 2019
1 2 32019 3 2019
2 3 52019 5 2019
3 5 102019 10 2019
不使用assign
改变原始数据帧
df.assign(**dict(zip(['Month', 'Year'], np.divmod(df.Date, 10000))))
ID Date Month Year
0 1 22019 2 2019
1 2 32019 3 2019
2 3 52019 5 2019
3 5 102019 10 2019
采用:
s=pd.to_datetime(df.pop('Date'),format='%m%Y') #convert to datetime and pop deletes the col
df['Month'],df['Year']=s.dt.month,s.dt.year #extract month and year
print(df)
ID Month Year
0 1 2 2019
1 2 3 2019
2 3 5 2019
3 5 10 2019
str.extract
可以处理棘手的部分,确定月份是否有1位或2位数。
(df['Date'].astype(str)
.str.extract(r'^(?P<Month>\d{1,2})(?P<Year>\d{4})$')
.astype(int))
Month Year
0 2 2019
1 3 2019
2 5 2019
3 10 2019
如果保证您的数字只有5位或6位数(如果没有,请使用上面的str.extract
),您也可以使用字符串切片:
u = df['Date'].astype(str)
df['Month'], df['Year'] = u.str[:-4], u.str[-4:]
df
ID Date Month Year
0 1 22019 2 2019
1 2 32019 3 2019
2 3 52019 5 2019
3 5 102019 10 2019
使用//
和%
df['Month'], df['Year'] = df.Date//10000,df.Date%10000
df
Out[528]:
ID Date Month Year
0 1 22019 2 2019
1 2 32019 3 2019
2 3 52019 5 2019
3 5 102019 10 2019
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.