繁体   English   中英

如何根据两个条件将数据框的单元格值相乘?

[英]How can i multiply a cell value of a dataframe based on two condition?

我有这个数据框

import numpy as np
import pandas as pd

data = {'month': ['5','5','6', '7'], 'condition': ["yes","no","yes","yes"],'amount': [500,200, 500, 500]}

和两个值:

inflation5 = 1.05
inflation6 = 1.08
inflation7 = 1.08

我需要知道当“月”列的值为 5 且“条件”列的值为“是”时,如何将“金额”列的单元格乘以值通胀 5,并将“金额”列的单元格相乘当“月”列值为 6 且“条件”列值为“是”时,通过值通胀 6,与第 7 个月相同。但我需要第 6 个月的计算基于新计算的月份值5,第 7 个月的计算基于第 6 个月的新计算值。为了更好地解释这一点,值 500 是一个估计值,需要根据经期通货膨胀(累积)进行更新。 “金额”列的预期输出:[525,200, 567, 612.36]

谢谢

为此,我将使用 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

我建议使用不同的方法来提高效率。

使用字典存储膨胀,然后您可以简单地在单个矢量调用中更新:

inflations = {'5': 1.05, '6': 1.08}

mask = df['condition'].eq('yes')
df.loc[mask, 'amount'] *= df.loc[mask, 'month'].map(inflations)

注意。 如果您可能在字典中缺少月份,请使用df.loc[mask, 'month'].map(inflations).fillna(1)代替df.loc[mask, 'month'].map(inflations)

输出:

  month condition  amount
0     5       yes     525
1     5        no     200
2     6       yes    6480
3     7        no    1873

更新的问题:累积通货膨胀

您可以制作一个系列并使用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)

输出:

  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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM