我有這個資料框
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]
謝謝
uj5u.com熱心網友回復:
我建議使用不同的方法來提高效率。
使用字典存盤膨脹,然后您可以簡單地在單個矢量呼叫中更新:
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
uj5u.com熱心網友回復:
為此,我將使用 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
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/473796.html
上一篇:C文本格式化程式字符計數已關閉
