python - Calculate new column in pandas based on certain criteria
问题描述
I am trying to multiple a two df based on certain values.
data = {'a':10,'b':20,'c':30} .
df1:
id,tag,factor
1,a ,20
2,b ,22
3,c ,25
my final result should look like something below:
id,factor,calc
1,20,200
2,22,440
3,24,750
The steps I have tried but giving error.
df['calc'] = df['factor'] * data.get(df['tag'])
解决方案
您可以使用pandas.Series.map和pandas.DataFrame.drop
df['calc'] = df['factor'] * df['tag'].map(data)
df.drop('tag', axis=1, inplace=True)
输出:
id factor calc
0 1 20 200
1 2 22 440
2 3 25 750
推荐阅读
- c# - 在没有通知的情况下将用户添加到组
- ios - 如何在选取图像后执行 Segue
- c# - asp.net mvc - 基于存储过程创建复杂视图
- abap - 下达采购订单后如何调用ABAP代码?
- c# - 如何调用“nuget restore”以恢复到托管在内部 nuget 服务器中的特定目录、特定包
- python - Pandas CustomBusinessDay 抵消只在一些假期工作
- c - 如何优化图像像素化程序
- excel - 如何通过自定义 Excel 功能区打开用户窗体
- asp.net-web-api - 带有接受标头和 url 参数的 Web API 内容协商格式化程序
- spring - 使用@Value Spring Annotation 从.yaml 读取的属性映射的正确用法是什么