Pandas DataFrame DataFrame.assign() 函数

Python Pandas DataFrame.assign() 函数将新的列分配给 DataFrame

pandas.DataFrame.assign() 语法

DataFrame.assign(**kwargs)

参数

**kwargs 关键字参数,要分配给 DataFrame 的列名作为关键字参数传递

返回值

它返回 DataFrame 对象,并将新的列和现有的列一起分配。

示例代码: DataFrame.assign() 方法分配一列

import pandas as pd
df = pd.DataFrame({'Cost Price':
                   [100, 200],
                   'Selling Price':
                   [200, 400]})
new_df=df.assign(Profit=df["Selling Price"]-
                        df["Cost Price"])
print(new_df)

调用者 DataFrame

   Cost Price  Selling Price
0         100            200
1         200            400

输出:

   Cost Price  Selling Price  Profit
0         100            200     100
1         200            400     200

它将新的列 Profit 分配给 DataFrame,对应于 Selling PriceCost Price 列之间的差异。

我们也可以通过对可调用对象使用 lambda 函数为 df 分配新的列。

import pandas as pd
df = pd.DataFrame({'Cost_Price':
                   [100, 200],
                   'Selling_Price':
                   [200, 400]})
new_df=df.assign(Profit=lambda x:
                 x.Selling_Price-
                 x.Cost_Price)
print(new_df)

调用的对象 DataFrame

   Cost Price  Selling Price
0         100            200
1         200            400

输出:

   Cost_Price  Selling_Price  Profit
0         100            200     100
1         200            400     200

示例代码:DataFrame.assign() 方法分配多列

import pandas as pd
df = pd.DataFrame({'Cost_Price':
                   [100, 200],
                   'Selling_Price':
                   [200, 400]})
new_df=df.assign(Cost_Price_Euro =
                 df['Cost_Price']*1.11,
                  Selling_Price_Euro =
                 df['Selling_Price']*1.11)
print(new_df)

调用者 DataFrame

   Cost Price  Selling Price
0         100            200
1         200            400

输出:

   Cost_Price  Selling_Price  Cost_Price_Euro  Selling_Price_Euro
0         100            200            111.0               222.0
1         200            400            222.0               444.0

它将两列新的 Cost_Price_EuroSelling_Price_Euro 分配给 df,这两列分别来自现有的 Cost_PriceSelling_Price

我们也可以使用 lambda 函数将多个列分配给 df,用于调用对象。

import pandas as pd
df = pd.DataFrame({'Cost_Price':
                   [100, 200],
                   'Selling_Price':
                   [200, 400]})
new_df=df.assign(Cost_Price_Euro =
                 lambda x: x.Cost_Price*1.11,
                 Selling_Price_Euro =
                 lambda x: x.Selling_Price*1.11)
print(new_df)

调用的对象 DataFrame 为,

   Cost Price  Selling Price
0         100            200
1         200            400

输出:

   Cost_Price  Selling_Price  Cost_Price_Euro  Selling_Price_Euro
0         100            200            111.0               222.0
1         200            400            222.0               444.0