【问题标题】:What is the way to add an index column in Dask when reading from a CSV?从 CSV 读取时在 Dask 中添加索引列的方法是什么?
【发布时间】:2019-10-23 14:21:58
【问题描述】:

我正在尝试处理一个相当大的数据集,该数据集在一次加载时使用 Pandas 无法放入内存,因此我使用的是 Dask。但是,在使用 read_csv 方法时,一旦读取数据集,我很难将唯一 ID 列添加到数据集中。我不断收到错误消息(请参阅代码)。我正在尝试创建一个索引列,以便可以将该新列设置为数据的索引,但错误似乎是告诉我在创建列之前先设置索引。

代码

df = dd.read_csv(r'path\to\file\file.csv')  # File does not have a unique ID column, so I have to create one.
df['index_col'] = dd.from_array(np.arange(len(pc_df)))  # Trying to add an index column and fill it
# ValueError: Not all divisions are known, can't align partitions. Please use `set_index` to set the index.

更新

使用range(1, len(df) + 1 将错误更改为:TypeError: Column assignment doesn't support type range

【问题讨论】:

    标签: python pandas dataframe indexing dask


    【解决方案1】:

    是的,如果不通读 CSV 文件,很难知道每个块中的行数,因此如果数据集跨越多个分区,则很难生成像 0, 1, 2, 3, ... 这样的索引。

    一种方法是创建一列:

    df["idx"] = 1
    

    然后调用 cumsum

    df["idx"] = df["idx"].cumsum()
    

    但请注意,这确实为支持您的数据框的任务图添加了一堆依赖项,因此某些操作可能不像以前那样并行。

    【讨论】:

    • 我会试一试,告诉你进展如何!当数据集跨越多个分区并且您从 csv 加载数据时,这通常是要走的路吗?
    • 通常人们不再期待一致的递增索引。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-02-14
    • 2019-07-16
    • 1970-01-01
    • 2013-12-05
    • 1970-01-01
    • 2010-09-24
    • 1970-01-01
    相关资源
    最近更新 更多