【问题标题】:variable column name in dask assign() or apply()dask assign() 或 apply() 中的变量列名
【发布时间】:2015-11-06 09:47:17
【问题描述】:

我的代码可以在 pandas 中使用,但我无法将其转换为使用 dask。有一个部分解决方案here,但它不允许我使用变量作为我正在创建/分配的列的名称。

这是有效的pandas 代码:

percent_cols = ['num_unique_words', 'num_words_over_6']

def find_fraction(row, col):
    return row[col] / row['num_words']

for c in percent_cols:
    df[c] = df.apply(find_fraction, col=c, axis=1)

这是 dask 代码,它不能满足我的要求:

data = dd.from_pandas(df, npartitions=8)

for c in percent_cols:
    data = data.assign(c = data[c] / data.num_words)

这会将结果分配给一个名为 c 的新列,而不是修改 data[c] 的值(我想要的)。如果我可以将列名作为变量,那么创建一个新列会很好。例如,如果这有效:

for c in percent_cols:
    name = c + "new"
    data = data.assign(name = data[c] / data.num_words)

出于显而易见的原因,python 不允许在 = 左侧的表达式并忽略 name 的先前值。

如何使用变量作为我要分配到的列的名称?循环的迭代次数远远超过我愿意复制/粘贴的次数。

【问题讨论】:

    标签: python pandas dask


    【解决方案1】:

    这可以解释为 Python 语言问题:

    问题:如何在关键字参数中使用变量的值作为名称?

    答案:使用字典和**解包

    c = 'name'
    f(c=5)       # 'c' is used as the keyword argument name, not what we want
    f(**{c: 5})  # 'name' is used as the keyword argument name, this is great
    

    Dask.dataframe 解决方案

    对于您的特定问题,我建议如下:

    d = {col: df[col] / df['num_words'] for col in percent_cols}
    df = df.assign(**d)
    

    考虑用 Pandas 也这样做

    .assign 方法在 Pandas 中也可用,并且可能比使用 .apply 更快。

    【讨论】:

    • 您能解释一下d = 行中发生了什么吗?
    • 我们制作了一个字典,将列名映射到我们想要放入数据框中的新列。这与调用 assign 的 for 循环相同。
    猜你喜欢
    • 2013-04-23
    • 1970-01-01
    • 2016-09-28
    • 2018-12-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多