pandas.DataFrame.assign#
- DataFrame.assign(**kwargs)[源代码]#
为 DataFrame 分配新列。
返回一个新对象,其中包含所有原始列以及新列。已重新分配的现有列将被覆盖。
- 参数:
- **kwargs可调用对象或 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
或使用
pandas.col()>>> df.assign(temp_f=pd.col("temp_c") * 9 / 5 + 32) 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, ... ) temp_c temp_f temp_k Portland 17.0 62.6 290.15 Berkeley 25.0 77.0 298.15