简体   繁体   English

python从csv读取日期和时间

[英]python read date and time from csv

my data looks like that: 我的数据如下所示:

GIdx,Date,num,Time
1,11/28/2012,20,10:05:50
1,11/28/2012,20,10:05:50
2,11/28/2012,20,10:09:24
2,11/28/2012,20,10:09:24
2,11/28/2012,20,10:09:25
2,11/28/2012,20,10:09:25
2,11/28/2012,20,10:09:26
3,11/28/2012,20,10:09:34
3,11/28/2012,20,10:09:34

i try to read column Date as datetime and column Time as time but when I check the their type I get Series : 我尝试将Date列读取为datetime并将Time列读取为time但是当我检查其类型时,我会得到Series

type(df['Date'])

class pandas.core.series.Series

type(df_original['Time'])

class pandas.core.series.Series

I did something like: 我做了类似的事情:

df=pd.read_csv(filename,sep=",", header = 0, na_values=['NA'])

You can add to read_csv parameter parse_dates with columns where are dates and times : 您可以将带有datestimes列添加到read_csv参数parse_dates

import pandas as pd
import io

temp=u"""GIdx,Date,num,Time
1,11/28/2012,20,10:05:50
1,11/28/2012,20,10:05:50
2,11/28/2012,20,10:09:24
2,11/28/2012,20,10:09:24
2,11/28/2012,20,10:09:25
2,11/28/2012,20,10:09:25
2,11/28/2012,20,10:09:26
3,11/28/2012,20,10:09:34
3,11/28/2012,20,10:09:34"""
#after testing replace io.StringIO(temp) to filename
df = pd.read_csv(io.StringIO(temp), parse_dates=[['Date','Time']])


print (df)
            Date_Time  GIdx  num
0 2012-11-28 10:05:50     1   20
1 2012-11-28 10:05:50     1   20
2 2012-11-28 10:09:24     2   20
3 2012-11-28 10:09:24     2   20
4 2012-11-28 10:09:25     2   20
5 2012-11-28 10:09:25     2   20
6 2012-11-28 10:09:26     2   20
7 2012-11-28 10:09:34     3   20
8 2012-11-28 10:09:34     3   20

print (df.dtypes)
Date_Time    datetime64[ns]
GIdx                  int64
num                   int64
dtype: object

You can omit parameters sep="," , header = 0 and na_values=['NA'] , because there are by default: 您可以省略参数sep=","header = 0na_values=['NA'] ,因为默认情况下有:

df=pd.read_csv(filename,sep=",", header = 0, na_values=['NA'])


df=pd.read_csv(filename)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM