我可以建议以下...代码的键位是在最后两行...代码的其余部分是重新创建数据框...
# load your data
from StringIO import StringIO # import from io for python 3
data = """ Date, open, high, close, low, volume, price_change
2015-03-25 13:55:00, 15.37, 15.38, 15.35, 15.34, 1121.00, -0.02
2015-03-25 14:00:00, 15.36, 15.38, 15.36, 15.34, 595.00, 0.00
2015-03-25 14:05:00, 15.36, 15.38, 15.36, 15.35, 1369.01, 0.00
2015-03-25 14:10:00, 15.36, 15.40, 15.40, 15.36, 3215.55, 0.04
2015-03-25 14:15:00, 15.40, 15.45, 15.39, 15.39, 1563.45, -0.01"""
df = pd.read_csv(StringIO(data), header=0, index_col=None, skipinitialspace=True)
df.Date = pd.to_datetime(df.Date)
# now let's create the date and time columns you want
df['date_only'] = [x.date() for x in df['Date']]
df['time_only'] = [x.time() for x in df['Date']]
输出这给我如下...
In [8]: df
Out[8]:
Date open high close low volume price_change \
0 2015-03-25 13:55:00 15.37 15.38 15.35 15.34 1121.00 -0.02
1 2015-03-25 14:00:00 15.36 15.38 15.36 15.34 595.00 0.00
2 2015-03-25 14:05:00 15.36 15.38 15.36 15.35 1369.01 0.00
3 2015-03-25 14:10:00 15.36 15.40 15.40 15.36 3215.55 0.04
4 2015-03-25 14:15:00 15.40 15.45 15.39 15.39 1563.45 -0.01
date_only time_only
0 2015-03-25 13:55:00
1 2015-03-25 14:00:00
2 2015-03-25 14:05:00
3 2015-03-25 14:10:00
4 2015-03-25 14:15:00
这是值得注意的是,不同类型的数据创建。
In [62]: type(df.date_only[0])
Out[62]: datetime.date
In [63]: type(df.time_only[0])
Out[63]: datetime.time
In [64]: type(df.Date[0])
Out[64]: pandas.tslib.Timestamp
In [65]: df.info()
<class 'pandas.core.frame.DataFrame'>
Int64Index: 5 entries, 0 to 4
Data columns (total 9 columns):
Date 5 non-null datetime64[ns]
open 5 non-null float64
high 5 non-null float64
close 5 non-null float64
low 5 non-null float64
volume 5 non-null float64
price_change 5 non-null float64
date_only 5 non-null object
time_only 5 non-null object
dtypes: datetime64[ns](1), float64(6), object(2)
memory usage: 400.0+ bytes
上述以外的所有,你也许能达到你想用datetime64 [NS]对象(上述日期列)的系列新.DT访问属性是什么。这是在熊猫0.15.0中引入的。它允许您执行诸如df.Date.dt.year
之类的操作,以从datetime64 [ns]对象中获取年份。还有月,日,时,分,秒等。
不确定这里是什么意思。你想将字符串转换为时间戳吗?你是否将2001年的日期转换为1990年的日期? AAPL值也是不同的。你有没有日期时间,只想显示零分钟? – 2015-04-02 06:33:20
请同时显示'df.info()' – joris 2015-04-02 07:12:45
如果您的索引已经是datetmeindex,那么显示屏可能不会显示时间,因为它没有时间组件创建。 – EdChum 2015-04-02 07:20:04