【问题标题】:Dask Updating column similar to sql caseDask更新列类似sql case
【发布时间】:2020-09-22 14:01:44
【问题描述】:

我有一个带有 int64 类型的列“is_internal”的 dask 数据框。我想更新这个类似于 SQL case 语句:

 CASE WHEN ltrim(rtrim(is_internal)) = '1' then 'Internal' else 'External' END as type

将数据导入为:

import pandas as pd 
import dask.dataframe as dd
import time
t=time.process_time()
df_train = dd.read_csv(r"C:\test.bcp", sep='\t', sample=25000000)

通常在 pandas 中,我会做类似的事情,但这会占用大量空间,我对此有所限制。

df_train.loc[df_train['is_internal'] == 1, 'type'] = 'internal'
df_train.loc[df_train['is_internal'] == 0, 'type'] = 'external'

最好的方法是什么,不会占用大量空间/内存?

【问题讨论】:

    标签: python dataframe dask


    【解决方案1】:

    你不应该改变 Dask 对象。您可以使用.where 方法实现您想要的。不幸的是,许多人发现它的表述令人困惑。但在很多情况下,如果您想直接使用 pandas 方式继续,您可以使用 map_partition 包装您的代码:

    def simple_where(df):
        df.loc[df['is_internal'] == 1, 'type'] = 'internal'
        df.loc[df['is_internal'] == 0, 'type'] = 'external'
        return df
    
    df_out = df_train.map_partitions(simple_where)
    

    【讨论】:

    • 我收到错误 AttributeError: 'DataFrame' object has no attribute 'map_partitions'
    • 修改了问题以显示我如何导入数据。我不明白为什么 map_partitions 不可用。
    • df_train=df_train.compute() - 您刚刚将所有内容加载到 pandas 数据帧中,我们认为您没有足够的内存来执行此操作。
    • 刚刚想通了。我不在需要运行脚本的机器上,而是在桌面上工作。
    猜你喜欢
    • 1970-01-01
    • 2014-12-05
    • 1970-01-01
    • 2015-02-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-24
    • 1970-01-01
    相关资源
    最近更新 更多