2015-09-01 161 views
1

的日期我有一列看起來像:如何重新排列大熊貓數據幀在python

test1.Received 
Out[9]: 
0  01/01/2015 17:25 
1  02/01/2015 11:43 
2  04/01/2015 18:21 
3  07/01/2015 16:17 
4  12/01/2015 20:12 
5  14/01/2015 11:09 
6  15/01/2015 16:05 
7  16/01/2015 21:02 
8  26/01/2015 03:00 
9  27/01/2015 08:32 
10  30/01/2015 11:52 

這代表了時間標記爲年月日小時分鐘。我想重新排列日期爲年月日小時分鐘。因此,它看起來像:

test1.Received 
Out[9]: 
0  2015/01/01 17:25 
1  2015/01/02 11:43 
... 
+0

你希望他們爲字符串? –

+0

作爲一個字符串,它應該很好。通過使用函數pd.to_datetime字符串應該再次變成datetime64 [ns] –

回答

1

只需使用pd.to_datetime:

In [33]: 
import pandas as pd 
pd.to_datetime(df['date']) 
Out[33]: 
index 
0 2015-01-01 17:25:00 
1 2015-02-01 11:43:00 
2 2015-04-01 18:21:00 
3 2015-07-01 16:17:00 
4 2015-12-01 20:12:00 
5 2015-01-14 11:09:00 
6 2015-01-15 16:05:00 
7 2015-01-16 21:02:00 
8 2015-01-26 03:00:00 
9 2015-01-27 08:32:00 
10 2015-01-30 11:52:00 
Name: date, dtype: datetime64[ns] 

你的情況:

pd.to_datetime(test1['Received']) 

應該只是工作

如果你想改變顯示格式那麼你需要解析爲日期時間,然後apply`datetime.strftime:

In [35]: 
pd.to_datetime(df['date']).apply(lambda x: dt.datetime.strftime(x, '%m/%d/%y %H:%M:%S')) 

Out[35]: 
index 
0  01/01/15 17:25:00 
1  02/01/15 11:43:00 
2  04/01/15 18:21:00 
3  07/01/15 16:17:00 
4  12/01/15 20:12:00 
5  01/14/15 11:09:00 
6  01/15/15 16:05:00 
7  01/16/15 21:02:00 
8  01/26/15 03:00:00 
9  01/27/15 08:32:00 
10 01/30/15 11:52:00 
Name: date, dtype: object 

所以上面現在顯示月/日/年,你的情況下面應該工作:

pd.to_datetime(test1['Received']).apply(lambda x: dt.datetime.strftime(x, '%y/%m/%d %H:%M:%S')) 

編輯

它看起來像你需要通過PARAM dayfirst=Trueto_datetime

In [45]: 
pd.to_datetime(df['date'], format('%d/%m/%y %H:%M:%S'), dayfirst=True).apply(lambda x: dt.datetime.strftime(x, '%m/%d/%y %H:%M:%S')) 

Out[45]: 
index 
0  01/01/15 17:25:00 
1  01/02/15 11:43:00 
2  01/04/15 18:21:00 
3  01/07/15 16:17:00 
4  01/12/15 20:12:00 
5  01/14/15 11:09:00 
6  01/15/15 16:05:00 
7  01/16/15 21:02:00 
8  01/26/15 03:00:00 
9  01/27/15 08:32:00 
10 01/30/15 11:52:00 
Name: date, dtype: object 
+0

我嘗試了第一行代碼,但我得到:TypeError:描述符'strftime'需要'datetime.date'對象,但收到'str' 。該列的dtype是對象 –

+0

你應該已經把你的數據的dtype放在你的文章中,如果它已經是'str',那麼'pd.to_datetime'只會解析這個罰款。 – EdChum

+0

問題是,當我做pd.to_datetime我得到一年的一個月而不是一年的一天,因爲我需要 –

1

熊貓有這個內置的,你可以指定你的日期時間格式 http://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_datetime.html。 使用infer_datetime_format

>>> import pandas as pd 
>>> i = pd.date_range('20000101',periods=100) 
>>> df = pd.DataFrame(dict(year = i.year, month = i.month, day = i.day)) 
>>> pd.to_datetime(df.year*10000 + df.month*100 + df.day, format='%Y%m%d') 
0 2000-01-01 
1 2000-01-02 
... 
98 2000-04-08 
99 2000-04-09 
Length: 100, dtype: datetime64[ns] 
1

可以使用datetime功能,從和字符串轉換。

# converts to date 
datetime.strptime(date_string, 'DD/MM/YYYY HH:MM') 

# converts to your requested string format 
datetime.strftime(date_string, "YYYY/MM/DD HH:MM:SS")