我的csv太大,无法读入内存,因此我尝试使用Dask解决我的问题。我是熊猫的常规用户,但缺乏使用Dask的经验。在我的数据中,有一个列“ MONTHSTART”,我希望将其作为日期时间对象进行交互。但是,尽管我的代码在Pandas示例中运行,但我似乎无法从Dask数据框中获得输出。
我在使用dask时已阅读了CSV
df = dd.read_csv(filename, dtype='str')
然后我将列的dtype转换为日期时间对象
def parse_dates(df):
return pd.to_datetime(df['MONTHSTART'], format='%d%b%Y')
meta = ('time', pd.Timestamp)
df.map_partitions(parse_dates, meta=meta)
最后,我尝试基于我的datetime列应用lambda函数来创建新列
df['MONTHS_AGO'] = df.apply(
lambda y: (dt.date.today().year - y['MONTHSTART'].dt.year) * 12 +
(dt.date.today().month - y['MONTHSTART'].dt.month),
axis=1,
meta=meta)
我不确定此处是否使用meta,否则我的代码将无法要求我指定meta。
没有元数据我得到
ValueError: Metadata inference failed, please provide `meta` keyword
有了meta我得到
AttributeError: ("'str' object has no attribute 'dt'", 'occurred at index 0')
我错误地解决了这个问题吗?是否有在Dask中应用lambda函数的技巧,而我却没有?
编辑: 我已经混淆了这些信息,并删除了很多列。我已尽力保持问题可以解决。 df.head(2).to_dict示例:
{'AGE_1': {0: '57', 1: '57'},
'APREM': {0: '347.08581006', 1: '347.08581006'},
'BUSINESS_1': {0: 'COMPUTERSERVICES', 1: 'COMPUTERSERVICES'},
'COMPULSORYEXCESSAD': {0: '0', 1: '0'},
'COVERTYPE': {0: 'Comprehensive', 1: 'Comprehensive'},
'DRIVINGRESTRICTION': {0: 'IOD', 1: 'IOD'},
'EARNEDTECH': {0: '35.438383793', 1: '15.356632977'},
'ENDDATE': {0: '13AUG2017', 1: '13AUG2017'},
'EXPMONTH': {0: 'EVY01APR2017', 1: 'EVY01AUG2017'},
'INFORCEATEOM': {0: '1', 1: '0'},
'LICENCETYPE_1': {0: 'FullUKCarLicence', 1: 'FullUKCarLicence'},
'MARITALSTATUS_1': {0: 'Partnered', 1: 'Partnered'},
'MILEAGERESTRICTION': {0: '8000', 1: '8000'},
'MIN_AGE': {0: '57', 1: '57'},
'MIN_EXP': {0: '18', 1: '18'},
'MIN_EXP_AGE': {0: '57', 1: '57'},
'MIN_EXP_LICENCETYPE': {0: 'FullUKCarLicence', 1: 'FullUKCarLicence'},
'MONTHEND': {0: '30APR2017', 1: '31AUG2017'},
'MONTHSTART': {0: '01APR2017', 1: '01AUG2017'},
'REGION': {0: 'East Anglia', 1: 'East Anglia'},
'STARTDATE': {0: '16FEB2017', 1: '16FEB2017'},
'TENURE': {0: '4th Renewal', 1: '4th Renewal'},
'TotalIncurredExclRI': {0: nan, 1: nan},
'VEHICLECOUNT': {0: '1', 1: '1'},
'VEHICLEKEPTOVERNIGHT': {0: 'Drive', 1: 'Drive'},
'VEHICLEMODIFICATION': {0: 'false', 1: 'false'},
'VEHICLENUMBER': {0: '1', 1: '1'},
'VEHICLEUSAGE': {0: 'Personal Business Use', 1: 'Personal Business Use'},
'VOLUNTARYEXCESS': {0: '250', 1: '250'}}
答案 0 :(得分:1)
您可能想重命名列并以您喜欢的格式转换日期,但这对我有用:
# First we create our df
import pandas as pd
import numpy as np
import dask.dataframe as dd
import datetime as dt
N = 10
df = pd.DataFrame({"date":pd.date_range(start='2017-01-01', periods=N),
"y":np.random.rand(N)})
df["date"] = df["date"].dt.strftime("%d%b%Y")
df.to_csv("data.csv", index=False)
然后
# read
df = dd.read_csv("data.csv", dtype='str')
# convert date to datetime
df["date"] = df["date"].astype("M8[us]")
# assign today date
td = dt.datetime.today()
# assign months_ago
df = df.assign(months_ago=((td.year - df["date"].dt.year)*12 +
td.month - df["date"].dt.month))
使用assign
无需处理meta