为什么Pandas不使用我的日期分析器读取csv?

2024-09-27 00:20:10 发布

您现在位置:Python中文网/ 问答频道 /正文

import numpy as np
import pandas as pd

def myDateParser(d):
    #in format: 10/02/2018, out format: 181002
    print("into myDateParser with ",d)
    return(d[8:]+d[0:2]+d[3:5])

nd=myDateParser('10/02/2018')
print("nd=",nd)


rawDataFile="Transactions.CSV"
data = pd.read_csv(rawDataFile, header=1, usecols=[0,1,2,3,4,5,6,7], 
parse_dates=True, date_parser=myDateParser) 
print(data.head())

在不应用我的日期分析器的情况下给出结果

into myDateParser with  10/02/2018
nd= 181002
         Date        Action    ...    Fees & Comm    Amount
0  10/02/2018           Buy    ...          $3.95  -$281.24
1  10/02/2018  Sell to Open    ...          $5.60   $184.40
2  10/02/2018          Sell    ...          $3.99  $2799.59
3  10/02/2018  Buy to Close    ...          $5.60  -$735.60
4  10/02/2018           Buy    ...          $3.95  -$319.95

[5 rows x 8 columns]

很明显,我不明白https://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html页上的说明


Tags: csvimportformatpandasreaddataaswith
2条回答

我想你在找converters

pd.read_csv(r'File.csv', converters ={'Data':myDateParser}) 

     Data
0  181002
1  181002
2  181002
3  181002

同时检查日期here

使用内置方法:

  • 不需要使用字符串切片创建自定义函数。你知道吗
df = pd.read_csv('data.csv', parse_dates=['Date'])
df.Date = df.Date.apply(lambda x: x.strftime('%y%m%d'))

      Date            Action    Fees & Comm    Amount
0   181002               Buy          $3.95   -281.24
1   181002      Sell to Open          $5.60    184.40
2   181002              Sell          $3.99   2799.59
3   181002      Buy to Close          $5.60   -735.60
4   181002               Buy          $3.95   -319.95

相关问题 更多 >

    热门问题