pandas.DataFrame.assign#
- DataFrame.assign(**kwargs)[源代码][源代码]#
将新列分配给 DataFrame。
返回一个包含所有原始列以及新列的新对象。重新分配的现有列将被覆盖。
- 参数:
- **kwargsdict of {str: callable or Series}
列名是关键字。如果值是可调用的,它们会在 DataFrame 上计算并分配给新列。可调用对象不能更改输入的 DataFrame(尽管 pandas 不会检查这一点)。如果值不可调用(例如 Series、标量或数组),它们会直接分配。
- 返回:
- DataFrame
一个新的 DataFrame,包含新列以及所有现有列。
参见
DataFrame.loc
通过标签选择DataFrame的一个子集。
DataFrame.iloc
按位置选择DataFrame的一个子集。
备注
在同一个
assign
中分配多个列是可能的。’**kwargs’ 中的后项可以引用 ‘df’ 中新建或修改的列;项按顺序计算并分配到 ‘df’ 中。例子
>>> df = pd.DataFrame({"temp_c": [17.0, 25.0]}, index=["Portland", "Berkeley"]) >>> df temp_c Portland 17.0 Berkeley 25.0
其中值是一个可调用对象,在 df 上进行评估:
>>> df.assign(temp_f=lambda x: x.temp_c * 9 / 5 + 32) 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) temp_c temp_f Portland 17.0 62.6 Berkeley 25.0 77.0
您可以在同一个分配中创建多个列,其中一个列依赖于在同一个分配中定义的另一个列:
>>> df.assign( ... temp_f=lambda x: x["temp_c"] * 9 / 5 + 32, ... temp_k=lambda x: (x["temp_f"] + 459.67) * 5 / 9, ... ) temp_c temp_f temp_k Portland 17.0 62.6 290.15 Berkeley 25.0 77.0 298.15