df.index[0]我想成為datetime.date(2006, 8, 27)。從文件讀取時,df = pd.read_csv(filePath,index_col="Date"),df.index[0]顯示為 string '2006-08-27'。我試過:dateparser = lambda s: datetime.datetime.strptime(s,"%Y-%m-%d").date()df = pd.read_csv(filePath,parse_dates=["Date"], date_parser=dateparser,index_col="Date")現在,df.index[0]顯示為Timestamp('2006-08-27 00:00:00').如何制作df.index[0]為datetime.date(2006, 8, 27)?使用的示例 csv:Date,Symbol,Series,Prev Close,Open,High,Low,Last,Close,VWAP,Volume,Turnover,Trades,Deliverable Volume,%Deliverble2006-08-27,,,,,,,,,,,,,,2006-08-28,ATFC,EQ,365.0,521.0,569.0,502.0,553.0,554.25,552.0,15166163,837176013020000.0,,3777529,0.249100000000000022006-08-29,ATFC,EQ,554.25,555.0,563.9,535.55,536.1,539.3,547.59,3929113,215153038915000.0,,727534,0.18522006-08-30,ATFC,EQ,539.3,537.0,542.9,521.5,529.0,528.1,529.55,2034983,107762957620000.0,,345064,0.16962006-08-31,ATFC,EQ,528.1,525.0,544.0,515.0,539.35,538.45,532.89,1670990,89044643830000.0,,286440,0.17142006-09-01,ATFC,EQ,538.45,539.0,549.0,535.1,541.35,541.85,542.46,1176195,63803856150000.0,,213842,0.1818
3 回答

慕的地6264312
TA貢獻1817條經驗 獲得超6個贊
已經有一個函數可以將數據更改為日期時間pd.to_datetime,而不是使用 lambda 函數
所以你可以做這樣的事情:
df?=?pd.read_csv(filePath,index_col="Date") df['Date']?=?pd.to_datetime(df['Date']?,format?=?'%Y-%m-%d') df['Date']?=?df['Date'].apply(lambda?x?:?x.date()) print(type(df['Date'][0]))
輸出
<class 'datetime.date'>
函數中還有一個格式參數,以匹配您的數據?格式
我認為你的格式是?format = '%Y-%m-%d'

藍山帝景
TA貢獻1843條經驗 獲得超7個贊
根據pandas.read_csv
,您還可以指定parse_dates = True
和infer_datetime_format = True
參數,讓 pandas 嘗試從您設置為 date 的索引中解析日期。如:
df?=?pd.read_csv(filePath,index_col="Date",parse_dates=True,infer_datetime_format=True)

慕斯王
TA貢獻1864條經驗 獲得超2個贊
無法獲得任何 oneliner。
df = pd.read_csv(filePath) # load dataframe
df["Date"]=df["Date"].apply(lambda s: datetime.datetime.strptime(s,"%Y-%m-%d").date()) # convert Date column items to datetime.date
df.set_index('Date', inplace=True) # set Date as row index
添加回答
舉報
0/150
提交
取消