【问题标题】:Can I use Python asyncio to slice and save DataFrame in a loop?我可以使用 Python asyncio 在循环中切片和保存 DataFrame 吗?
【发布时间】:2017-07-17 21:40:02
【问题描述】:

正如标题所说 - 是否可以编写一个异步事件循环,将 DataFrame 按特定列中的唯一值切片并将其保存在我的驱动器上?也许更重要的是 - 它更快吗?

我尝试过的是这样的:

async def a_split(dist,df):
    temp_df = df[df.district == dist]
    await temp_df.to_csv('{}.csv'.format(d))

async def m_lp(df):
    for dist in df.district.unique().tolist():
        await async_slice(dist,df)

loop = asyncio.get_event_loop()

loop.run_until_complete(m_lp(dfTotal))  
loop.close() 

但我收到以下错误:

TypeError: object NoneType can't be used in 'await' expression

如果我的尝试不是很明显,我对 asyncio 还是很陌生,我不确定它是如何工作的。抱歉,如果这是一个愚蠢的问题。

如果 asyncio 不是这项工作的好工具 - 还有更好的工具吗?

编辑:

完整的追溯如下:

    ---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-22-2bc2373d2920> in <module>()
      2 loop = asyncio.get_event_loop()
      3 
----> 4 loop.run_until_complete(m_lp(dfTotal))
      5 loop.close()

C:\Users\5157213\AppData\Local\Continuum\Anaconda3\envs\python36\lib\asyncio\base_events.py in run_until_complete(self, future)
    464             raise RuntimeError('Event loop stopped before Future completed.')
    465 
--> 466         return future.result()
    467 
    468     def stop(self):

<ipython-input-20-9e91c0b1b06f> in m_lp(df)
      1 async def m_lp(df):
      2     for dist in df.district.unique().tolist():
----> 3         await a_split(dist,df)

<ipython-input-18-200b08417159> in a_split(dist, df)
      1 async def a_split(dist,df):
      2     temp = df[df.district == dist]
----> 3     await temp.to_csv('C:/Users/5157213/Desktop/Portfolio/{}.csv'.format(dist))

TypeError: object NoneType can't be used in 'await' expression

【问题讨论】:

  • edit 包含完整回溯的问题。就目前而言,我们无法确定指的是哪个await
  • 已编辑 - 看起来它指的是 df.to_csv 行旁边的 await,但 await 都没有返回任何东西

标签: python pandas dataframe python-asyncio


【解决方案1】:

据我所知,Pandas 中没有异步支持。我认为单线程基于事件的体系结构不是系统中的最佳工具,在这些系统中,您有许多其他选项来处理负载/大数据,即。对于大型数据集,请查看 dask

您得到的错误是因为您尝试await 函数Dataframe.to_csv 不返回Future(或任何其他等待对象),而是None

【讨论】:

    猜你喜欢
    • 2018-10-13
    • 2013-09-26
    • 2019-03-30
    • 2019-05-10
    • 2022-08-02
    • 2018-06-21
    • 1970-01-01
    • 2018-06-06
    • 1970-01-01
    相关资源
    最近更新 更多