# Pandas DataFrame DataFrame.assign() 函式

Suraj Joshi 2023年1月30日

Python Pandas DataFrame.assign() 函式將新的列分配給 DataFrame

## pandas.DataFrame.assign() 語法

DataFrame.assign(**kwargs)

### 引數

**kwargs 關鍵字引數，要分配給 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)

Cost Price  Selling Price
0         100            200
1         200            400

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

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)

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)

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

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)

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

Suraj Joshi is a backend software engineer at Matrice.ai.