![](/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.