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 Price
和 Cost 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_Euro
和 Selling_Price_Euro
分配给 df
,这两列分别来自现有的 Cost_Price
和 Selling_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
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布,任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站。本站所有源码与软件均为原作者提供,仅供学习和研究使用。如您对本站的相关版权有任何异议,或者认为侵犯了您的合法权益,请及时通知我们处理。