2015-09-01 164 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")