如何以相反的顺序在 pandas 中保存拆分数据? [英] How to save split data in panda in reverse order?

查看:52
本文介绍了如何以相反的顺序在 pandas 中保存拆分数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您可以使用它来创建数据框:

You can use this to create the dataframe:

xyz = pd.DataFrame({'release' : ['7 June 2013', '2012', '31 January 2013',
                                 'February 2008', '17 June 2014', '2013']})

我正在尝试使用以下命令将数据拆分并保存到名为日、月和年"的 3 列中:

I am trying to split the data and save, them into 3 columns named "day, month and year", using this command:

dataframe[['day','month','year']] = dataframe['release'].str.rsplit(expand=True) 

结果数据框是:数据框

正如你所看到的,当它得到 3 个字符串时它工作得很好,但是当它得到少于 3 个字符串时,它会将数据保存在错误的位置.

As you can see, that it works perfectly when it gets 3 strings, but whenever it is getting less then 3 strings, it saves the data at the wrong place.

我尝试了 split 和 rsplit,两者都给出了相同的结果.在正确的位置获取数据的任何解决方案?

I have tried split and rsplit, both are giving the same result. Any solution to get the data at the right place?

最后一个是 year 并且它在所有条件下都存在,它应该是第一个被保存的,然后是月,如果它存在,否则什么都没有,并且应该以同样的方式存储日期.

The last one is year and it is present in every condition , it should be the first one to be saved and then month if it is present otherwise nothing and same way the day should be stored.

推荐答案

你可以

In [17]: dataframe[['year', 'month', 'day']] = dataframe['release'].apply(
                                                    lambda x: pd.Series(x.split()[::-1]))
In [18]: dataframe
Out[18]:
           release  year     month  day
0      7 June 2013  2013      June    7
1             2012  2012       NaN  NaN
2  31 January 2013  2013   January   31
3    February 2008  2008  February  NaN
4     17 June 2014  2014      June   17
5             2013  2013       NaN  NaN

这篇关于如何以相反的顺序在 pandas 中保存拆分数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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