我正在根据条件计算净余额的值,我希望将其完全存储在新变量中。新变量应将此计算值存储为整数或浮点数,而不应存储为数组
我尝试了以下代码:
#variable = something if condition else something_else
mar_final_bal = x_start_bal+df2['credit_line']+df2['Net_Balance'] if
df2['month' == 'March-2016']
apr_final_bal = mar_final_bal+df2['credit_line']+df2['Net_Balance'] if
df2['month' == 'Apr-2016']
mar_final_bal和apr_final_bal是我要使用右侧条件创建的两个变量
答案 0 :(得分:0)
很明显,您是第一次使用Pandas。该语法看起来比pandas代码更像伪代码。 IIUC,这就是您的意思:
mar_final_bal = x_start_bal+df2.loc[df2['month'] == 'March-2016', 'credit_line'].sum() + df2.loc[df2['month'] == 'March-2016', 'Net_Balance'].sum()
apr_final_bal = mar_final_bal+df2.loc[df2['month'] == 'Apr-2016', 'credit_line'].sum() + df2.loc[df2['month'] == 'Apr-2016', 'Net_Balance'].sum()