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
转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处
本文地址:
相关文章
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 系列日期时间转换为字符串