Datetime 从pandas(python)数据帧对象中提取小时、日期和月份
使用熊猫数据帧Datetime 从pandas(python)数据帧对象中提取小时、日期和月份,datetime,python-3.x,pandas,python-datetime,Datetime,Python 3.x,Pandas,Python Datetime,使用熊猫数据帧df: x y 0 29-04-2014 07:40:52 07:40:52 1 29-04-2014 07:59:25 07:15:00 2 NaN NaN 3 29-04-2014 08:16:12 07:45:00 4 09-05-2014 08:19:14 07:30:00 5 23-04-2014 08:27:16
df
:
x y
0 29-04-2014 07:40:52 07:40:52
1 29-04-2014 07:59:25 07:15:00
2 NaN NaN
3 29-04-2014 08:16:12 07:45:00
4 09-05-2014 08:19:14 07:30:00
5 23-04-2014 08:27:16 08:30:00
6 29-04-2014 08:37:16 07:00:00
7 NaN NaN
8 29-04-2014 08:41:16 07:30:00
9 25-03-2014 08:42:16 07:30:00
如果列x
包含日期月年小时:分钟:秒
和y
存储小时:分钟:秒
,如何仅提取:
x
的日期[29
自第0行开始]x
列第0行起的月份[04
或April
x
的月份和日期[29-04
或4月29日
自第0行开始]x
和y
的小时和分钟[07-40
自第0行开始]df=pd.read_表(“C:\data.txt,sep='\t'”)
但它最初来自MS Excel或MS Access
当我运行df.dtypes
时,我得到
x object
y object
dtype: object
我正在使用Python3.4
开发Pandas版本0.14.1
示例数据帧
import numpy as np
import pandas a pd
df = pd.DataFrame({'x': ['29-04-2014 07:40:52', np.nan, '29-04-2014 08:16:16','29-04-2014 08:19:56', '29-04-2014 08:27:20'],
'y': ['07:40:52', '07:15:00', np.nan, '07:45:00', '07:30:00']})
我认为熊猫的方法是把x作为索引,然后你可以使用一些简单的方法来提取你想要的。非同步方式是使用datetime模块 熊猫路。。。作为背景,您可以阅读周围的timeseries数据,这是非常好的 设置一些示例数据:
n = 10
df = pd.DataFrame(pd.date_range('1/1/2000', periods=n))
df.columns = ['x']
df['z'] = rand(n)
df.set_index('x', inplace=True)
print df
z
x
2000-01-01 0.863064
2000-01-02 0.980083
2000-01-03 0.278810
2000-01-04 0.960890
2000-01-05 0.309591
2000-01-06 0.662498
2000-01-07 0.802367
2000-01-08 0.403791
2000-01-09 0.981172
2000-01-10 0.342935
请注意,您的数据似乎不是以x为索引设置的。这是重要的一步
将日期作为时间点击后,您可以访问所需内容:
df['d'] = df.index.day
df['m'] = df.index.month
df['y'] = df.index.year
print df
z y d m
x
2000-01-01 0.863064 2000 1 1
2000-01-02 0.980083 2000 2 1
2000-01-03 0.278810 2000 3 1
2000-01-04 0.960890 2000 4 1
2000-01-05 0.309591 2000 5 1
2000-01-06 0.662498 2000 6 1
2000-01-07 0.802367 2000 7 1
2000-01-08 0.403791 2000 8 1
2000-01-09 0.981172 2000 9 1
2000-01-10 0.342935 2000 10 1
非常感谢。我有其他类似条目的列,但其中只有一列可以作为索引。