熊猫拆卸柱子

时间:2016-08-24 08:53:08

标签: python date pandas dataframe split

从pandas http://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_datetime.html的文档中可以看到多列的集合,例如:解释了日期列到单个列。

>>> df = pd.DataFrame({'year': [2015, 2016],
                        'month': [2, 3],
                        'day': [4, 5]})
>>> pd.to_datetime(df) 
0   2015-02-04 1   2016-03-05 dtype: datetime64[ns]

但我怎样才能进行相反的转变?

2 个答案:

答案 0 :(得分:2)

您可以使用dt访问者访问日期时间的组成部分,请注意to_datetime返回Series,以便我转换为df以添加列:

In [71]:
df1 = pd.to_datetime(df)
df1 = df1.to_frame()
df1 = df1.rename(columns={0:'date'})
df1

Out[71]:
        date
0 2015-02-04
1 2016-03-05

In [72]:
df1['year'], df1['month'], df1['day'] = df1['date'].dt.year, df1['date'].dt.month, df1['date'].dt.day
df1

Out[72]:
        date  year  month  day
0 2015-02-04  2015      2    4
1 2016-03-05  2016      3    5

每个组件的dtypes为int64

In [73]:    
df1.info()

<class 'pandas.core.frame.DataFrame'>
RangeIndex: 2 entries, 0 to 1
Data columns (total 4 columns):
date     2 non-null datetime64[ns]
year     2 non-null int64
month    2 non-null int64
day      2 non-null int64
dtypes: datetime64[ns](1), int64(3)
memory usage: 144.0 bytes

答案 1 :(得分:1)

.dt.strftime('%Y %-m %-d').str.split()将撤消操作

df = pd.DataFrame({'year': [2015, 2016],
                        'month': [2, 3],
                        'day': [4, 5]})
pd.to_datetime(df)

0   2015-02-04
1   2016-03-05
dtype: datetime64[ns]
pd.to_datetime(df).dt.strftime('%Y %-m %-d').str.split()

0    [2015, 2, 4]
1    [2016, 3, 5]
dtype: object

或者使用花哨的正则表达式提取物

regex = r'(?P<year>\d+) (?P<month>\d+) (?P<day>\d+)'
pd.to_datetime(df).dt.strftime('%Y %-m %-d') \
    .str.extract(regex, expand=True).astype(int)

enter image description here

相关问题