dle*_*eal 11 python pandas dask
我正在尝试将我的数据帧的一列转换为datetime.在这里讨论之后https://github.com/dask/dask/issues/863我尝试了以下代码:
import dask.dataframe as dd
df['time'].map_partitions(pd.to_datetime, columns='time').compute()
Run Code Online (Sandbox Code Playgroud)
但我收到以下错误消息
ValueError: Metadata inference failed, please provide `meta` keyword
Run Code Online (Sandbox Code Playgroud)
究竟应该把什么放在元下?我应该在df中或仅在'time'列中放置所有列的字典吗?我应该放什么类型的?我尝试过dtype和datetime64,但到目前为止它们都没有.
谢谢你,我感谢你的指导,
更新
我将在这里包含新的错误消息:
1)使用时间戳
df['trd_exctn_dt'].map_partitions(pd.Timestamp).compute()
TypeError: Cannot convert input to Timestamp
Run Code Online (Sandbox Code Playgroud)
2)使用datetime和meta
meta = ('time', pd.Timestamp)
df['time'].map_partitions(pd.to_datetime,meta=meta).compute()
TypeError: to_datetime() got an unexpected keyword argument 'meta'
Run Code Online (Sandbox Code Playgroud)
3)只使用日期时间:陷入2%
In [14]: df['trd_exctn_dt'].map_partitions(pd.to_datetime).compute()
[ ] | 2% Completed | 2min 20.3s
Run Code Online (Sandbox Code Playgroud)
此外,我希望能够在日期中指定格式,就像我在pandas中所做的那样:
pd.to_datetime(df['time'], format = '%m%d%Y'
Run Code Online (Sandbox Code Playgroud)
更新2
更新到Dask 0.11后,我不再遇到meta关键字问题.不过,我无法在2GB数据帧上超过2%.
df['trd_exctn_dt'].map_partitions(pd.to_datetime, meta=meta).compute()
[ ] | 2% Completed | 30min 45.7s
Run Code Online (Sandbox Code Playgroud)
更新3
这样做得更好:
def parse_dates(df):
return pd.to_datetime(df['time'], format = '%m/%d/%Y')
df.map_partitions(parse_dates, meta=meta)
Run Code Online (Sandbox Code Playgroud)
我不确定这是否是正确的做法
MRo*_*lin 13
astype您可以使用该astype方法将系列的dtype转换为NumPy dtype
df.time.astype('M8[us]')
Run Code Online (Sandbox Code Playgroud)
可能还有一种指定Pandas样式dtype的方法(编辑欢迎)
当使用黑盒方法时map_partitions,dask.dataframe需要知道输出的类型和名称.在文档字符串中列出了几种方法map_partitions.
您可以使用正确的dtype和名称提供空的Pandas对象
meta = pd.Series([], name='time', dtype=pd.Timestamp)
Run Code Online (Sandbox Code Playgroud)
或者,您可以为(name, dtype)DataFrame 提供Series或dict 的元组
meta = ('time', pd.Timestamp)
Run Code Online (Sandbox Code Playgroud)
那一切都应该没问题
df.time.map_partitions(pd.to_datetime, meta=meta)
Run Code Online (Sandbox Code Playgroud)
如果你打电话map_partitions,df那么你需要提供所有的dtypes.但是在你的例子中并非如此.
我不确定这是否是正确的方法,但映射列对我有用:
df['time'] = df['time'].map(lambda x: pd.to_datetime(x, errors='coerce'))
Run Code Online (Sandbox Code Playgroud)
Dask还附带了to_timedelta,因此它也应该工作。
df['time']=dd.to_datetime(df.time,unit='ns')
Run Code Online (Sandbox Code Playgroud)
取值单位与pandas中的pd.to_timedelta相同。可以在这里找到。
这对我有用
ddf["Date"] = ddf["Date"].map_partitions(pd.to_datetime,format='%d/%m/%Y',meta = ('datetime64[ns]'))