[英]How can i multiply a cell value of a dataframe based on two condition?
I have this dataframe我有这个数据框
import numpy as np
import pandas as pd
data = {'month': ['5','5','6', '7'], 'condition': ["yes","no","yes","yes"],'amount': [500,200, 500, 500]}
and two values:和两个值:
inflation5 = 1.05
inflation6 = 1.08
inflation7 = 1.08
I need to know how can i multiply the cells of column 'amount' by the value inflation5 when the column 'month' value is 5 and the column 'condition' value is "yes", and also multiply the cells of column 'amount' by the value inflation6 when the column 'month' value is 6 and the column 'condition' value is "yes", and the same with month 7. But i need that calculation for the month 6 is based in the new calculated value of month 5, and the calculation for the month 7 is based in the new calculated value of month 6. In order to explain this better, the value 500 is an estimation that needs to be updated with mensual inflation (accumulative).我需要知道当“月”列的值为 5 且“条件”列的值为“是”时,如何将“金额”列的单元格乘以值通胀 5,并将“金额”列的单元格相乘当“月”列值为 6 且“条件”列值为“是”时,通过值通胀 6,与第 7 个月相同。但我需要第 6 个月的计算基于新计算的月份值5,第 7 个月的计算基于第 6 个月的新计算值。为了更好地解释这一点,值 500 是一个估计值,需要根据经期通货膨胀(累积)进行更新。 The expected output for column 'amount': [525,200, 567, 612.36] “金额”列的预期输出:[525,200, 567, 612.36]
Thanks谢谢
For this I would run through with an np.where, should make it easily readable, and expandable especially if you wanted to change the condition with a function.为此,我将使用 np.where 来完成,应该使其易于阅读和扩展,特别是如果您想使用函数更改条件。
df = pd.DataFrame(data)
df['Inflation'] = np.where((df['month'] == '5') & (df['condition'] == 'yes'), inflation5, 1)
df['Inflation'] = np.where((df['month'] == '6') & (df['condition'] == 'yes'), inflation6, df['Inflation'])
df['Total_Amount'] = df['amount'].values * df['Inflation'].values
I would suggest to use a different approach for efficiency.我建议使用不同的方法来提高效率。
Use a dictionary to store the inflations, then you can simply update in a single vectorial call:使用字典存储膨胀,然后您可以简单地在单个矢量调用中更新:
inflations = {'5': 1.05, '6': 1.08}
mask = df['condition'].eq('yes')
df.loc[mask, 'amount'] *= df.loc[mask, 'month'].map(inflations)
NB.注意。 if you possibly have missing months in the dictionary, use df.loc[mask, 'month'].map(inflations).fillna(1)
in place of df.loc[mask, 'month'].map(inflations)
如果您可能在字典中缺少月份,请使用df.loc[mask, 'month'].map(inflations).fillna(1)
代替df.loc[mask, 'month'].map(inflations)
output:输出:
month condition amount
0 5 yes 525
1 5 no 200
2 6 yes 6480
3 7 no 1873
You can craft a series and use a cumprod
:您可以制作一个系列并使用cumprod
:
inflations = {'5': 1.05, '6': 1.08, '7': 1.08}
mask = df['condition'].eq('yes')
s = pd.Series(inflations).cumprod()
df.loc[mask, 'amount'] *= df.loc[mask, 'month'].map(s).fillna(1)
Output:输出:
month condition amount
0 5 yes 525.00
1 5 no 200.00
2 6 yes 567.00
3 7 yes 612.36
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.