2016-08-24 50 views
2

從熊貓文檔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] 

但我該如何執行相反的轉換?

+0

對不起什麼是所需的輸出?你想把日期時間分解成它的組成部分?你可以做'df ['year'],df ['month'],df ['day'] = df ['Date']。dt.year,df ['Date']。dt.month,df [日期']。dt.day' – EdChum

+0

謝謝。這是所需的輸出。 –

回答

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

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 
+0

或者,您可以通過'df1.date.apply(operator.attrgetter('year','month','day'))' –

+0

@JonClements獲取組件,這會更簡潔,但我總是建議不要使用'apply'當存在矢量化解決方案時,雖然我確實發現它有些困惑,爲什麼某些'.str'和'.dt'操作有時會比'apply'或'map'慢,也會返回一個元組,所以您需要訪問每個元素 – EdChum