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
相关文章
Pandas DataFrame DataFrame.shift() 函数
发布时间:2024/04/24 浏览次数:133 分类:Python
-
DataFrame.shift() 函数是将 DataFrame 的索引按指定的周期数进行移位。
Python pandas.pivot_table() 函数
发布时间:2024/04/24 浏览次数:82 分类:Python
-
Python Pandas pivot_table()函数通过对数据进行汇总,避免了数据的重复。
Pandas read_csv()函数
发布时间:2024/04/24 浏览次数:254 分类:Python
-
Pandas read_csv()函数将指定的逗号分隔值(csv)文件读取到 DataFrame 中。
Pandas 多列合并
发布时间:2024/04/24 浏览次数:628 分类:Python
-
本教程介绍了如何在 Pandas 中使用 DataFrame.merge()方法合并两个 DataFrames。
Pandas loc vs iloc
发布时间:2024/04/24 浏览次数:837 分类:Python
-
本教程介绍了如何使用 Python 中的 loc 和 iloc 从 Pandas DataFrame 中过滤数据。
在 Python 中将 Pandas 系列的日期时间转换为字符串
发布时间:2024/04/24 浏览次数:894 分类:Python
-
了解如何在 Python 中将 Pandas 系列日期时间转换为字符串