【问题标题】:Pandas DataFrame.assign argumentsPandas DataFrame.assign 参数
【发布时间】:2017-06-25 09:04:16
【问题描述】:

问题

如何使用assign 返回添加了多个新列的原始 DataFrame 的副本?

期望的结果

df = pd.DataFrame({'A': range(1, 5), 'B': range(11, 15)})
>>> df.assign({'C': df.A.apply(lambda x: x ** 2), 'D': df.B * 2})
   A   B   C   D
0  1  11   1  22
1  2  12   4  24
2  3  13   9  26
3  4  14  16  28

尝试

上面的例子导致:

ValueError: Wrong number of items passed 2, placement implies 1.

背景

Pandas 中的assign 函数将相关数据框的副本加入到新分配的列中,例如

df = df.assign(C=df.B * 2)
>>> df
   A   B   C
0  1  11  22
1  2  12  24
2  3  13  26
3  4  14  28

此函数的0.19.2 documentation 表示可以将多个列添加到数据框中。

可以在同一个 assign 中分配多个列,但不能引用在同一个 assign 调用中创建的其他列。

另外:

参数:
kwargs : 关键字,值对

关键字是列名。

函数的源代码声明它接受字典:

def assign(self, **kwargs):
    """
    .. versionadded:: 0.16.0
    Parameters
    ----------
    kwargs : keyword, value pairs
        keywords are the column names. If the values are callable, they are computed 
        on the DataFrame and assigned to the new columns. If the values are not callable, 
        (e.g. a Series, scalar, or array), they are simply assigned.

    Notes
    -----
    Since ``kwargs`` is a dictionary, the order of your
    arguments may not be preserved. The make things predicatable,
    the columns are inserted in alphabetical order, at the end of
    your DataFrame. Assigning multiple columns within the same
    ``assign`` is possible, but you cannot reference other columns
    created within the same ``assign`` call.
    """

    data = self.copy()

    # do all calculations first...
    results = {}
    for k, v in kwargs.items():

        if callable(v):
            results[k] = v(data)
        else:
            results[k] = v

    # ... and then assign
    for k, v in sorted(results.items()):
        data[k] = v

    return data

【问题讨论】:

  • 我认为文档应该更清楚地说明如何使用多个列来避免与提供的示例产生歧义
  • @JJJ 我拒绝了您的标签编辑,因为这个问题与 python 无关。请参阅有关元的相关帖子。 meta.stackoverflow.com/questions/303459/…

标签: pandas


【解决方案1】:

您可以通过提供每个新列作为关键字参数来创建多个列:

df = df.assign(C=df['A']**2, D=df.B*2)

我通过使用 ** 将字典解压缩为关键字参数,让您的示例字典正常工作:

df = df.assign(**{'C': df.A.apply(lambda x: x ** 2), 'D': df.B * 2})

看起来assign 应该可以带字典,但根据您发布的源代码,目前似乎不支持它。

结果输出:

   A   B   C   D
0  1  11   1  22
1  2  12   4  24
2  3  13   9  26
3  4  14  16  28

【讨论】:

  • 到目前为止,这是我发现使用带有空格的列名的分配函数的唯一方法,因为,AFAIK,Python kwargs 不能拥有它们。
猜你喜欢
  • 2020-07-13
  • 1970-01-01
  • 2020-05-08
  • 2017-06-18
  • 2023-01-19
  • 1970-01-01
  • 2014-08-16
  • 2020-04-14
相关资源
最近更新 更多