我有以下的原始數據,熊貓read_csv:解析時間字段正確
TranID,TranDate,TranTime,TranAmt
A123456,20160427,02:18,9999.53
B123457,20160426,02:48,26070.33
C123458,20160425,03:18,13779.56
A123459,20160424,03:18,18157.26
B123460,20160423,04:18,215868.15
C123461,20160422,04:18,23695.25
A123462,20160421,05:18,57
B123463,20160420,05:18,64594.24
C123464,20160419,06:18,47890.91
A123465,20160427,06:18,14119.74
B123466,20160426,07:18,2649.6
C123467,20160425,07:18,16757.38
A123468,20160424,08:18,8864.78
B123469,20160423,08:18,26254.69
C123470,20160422,09:18,13206.98
A123471,20160421,09:18,15872.45
B123472,20160420,10:18,197621.18
C123473,20160419,10:18,21048.72
,我試圖導入原始數據採用PD read_csv,
Try1
import numpy as np
import pandas as pd
df = pd.read_csv('MyTest.csv', sep=',', header=0, parse_dates=['TranDate'],
usecols=['TranID','TranDate','TranTime','TranAmt'],
engine='python')
print(df.dtypes)
df[:5]
輸出1
TranID object
TranDate datetime64[ns]
TranTime object
TranAmt float64
dtype: object
Out[12]:
TranID TranDate TranTime TranAmt
0 A123456 2016-04-27 02:18 9999.53
1 B123457 2016-04-26 02:48 26070.33
2 C123458 2016-04-25 03:18 13779.56
3 A123459 2016-04-24 03:18 18157.26
4 B123460 2016-04-23 04:18 215868.15
Try2
import numpy as np
import pandas as pd
df = pd.read_csv('MyTest.csv', sep=',', header=0, parse_dates=['TranDate', 'TranTime'],
usecols=['TranID','TranDate','TranTime','TranAmt'],
engine='python')
print(df.dtypes)
df[:5]
輸出2
TranID object
TranDate datetime64[ns]
TranTime datetime64[ns]
TranAmt float64
dtype: object
Out[13]:
TranID TranDate TranTime TranAmt
0 A123456 2016-04-27 2016-04-27 02:18:00 9999.53
1 B123457 2016-04-26 2016-04-27 02:48:00 26070.33
2 C123458 2016-04-25 2016-04-27 03:18:00 13779.56
3 A123459 2016-04-24 2016-04-27 03:18:00 18157.26
4 B123460 2016-04-23 2016-04-27 04:18:00 215868.15
我的困惑是與TranTime列。在Try1中,它顯示正確,但dtype是對象。在Try2中,pd將當前日期添加到時間,並且dtype是日期時間。
我希望此TranTime列被視爲時間並希望使用pd的groupby或pivot_table執行聚合。 如果我使用Try1方法,對象dtype是否會影響我的聚合? 如果我使用Try2方法,是否需要去除日期部分以便使用時間部分?
我精通SAS,其中SAS有日期,時間和日期時間信息和格式,其中底層數據類型只是數字。因此,我與Python的對象和日期時間dtypes混淆。
感謝, Lobbie
非常感謝您的詳細解答。一切都很好,我今天學到了一些新東西。問候,Lobbie – Lobbie