maxframe.dataframe.DataFrame.assign#
- DataFrame.assign(**kwargs)[源代码]#
为 DataFrame 分配新列。返回一个包含所有原始列以及新列的新对象。重新分配的现有列将被覆盖。
- 参数:
**kwargs (dict of {str: callable or Series}) -- 列名是关键字。如果值是可调用的,则在 DataFrame 上计算并分配给新列。可调用对象不得更改输入 DataFrame(尽管 pandas 不会检查)。如果值不可调用(例如 Series、标量或数组),则直接分配。
- 返回:
一个包含所有现有列以及新列的新 DataFrame。
- 返回类型:
备注
可以在同一个
assign中分配多个列。'kwargs' 中后面的项可以引用 'df' 中新创建或修改的列;各项按顺序计算并分配到 'df' 中。示例
>>> import maxframe.dataframe as md >>> df = md.DataFrame({'temp_c': [17.0, 25.0]}, ... index=['Portland', 'Berkeley']) >>> df.execute() temp_c Portland 17.0 Berkeley 25.0
当值是可调用对象时,在 df 上进行求值:
>>> df.assign(temp_f=lambda x: x.temp_c * 9 / 5 + 32).execute() temp_c temp_f Portland 17.0 62.6 Berkeley 25.0 77.0
或者,可以通过直接引用现有的 Series 或序列来实现相同的行为:
>>> df.assign(temp_f=df['temp_c'] * 9 / 5 + 32).execute() temp_c temp_f Portland 17.0 62.6 Berkeley 25.0 77.0
你可以在同一个 assign 中创建多个列,其中一个列依赖于同一 assign 中定义的另一个列:
>>> df.assign(temp_f=lambda x: x['temp_c'] * 9 / 5 + 32, ... temp_k=lambda x: (x['temp_f'] + 459.67) * 5 / 9).execute() temp_c temp_f temp_k Portland 17.0 62.6 290.15 Berkeley 25.0 77.0 298.15