假设此数据帧:
vals = [['1.00.00.00', 'Total Assets', 1000], ['1.01.00.00', 'Cash', 200], ['1.02.00.00', 'Inventory', 800], ['1.02.01.00', 'Goods in process', 300], ['1.02.02.00', 'Goods for sale', 500], ['2.00.00.00', 'Liabilities', 750], ['2.01.00.00', 'Commercial Liabilities', 700], ['2.02.00.00', 'Other liabilities', 50], ['3.00.00.00', 'Net equity', 250]]
cols = ['account', 'name', 'balance']
df = pd.DataFrame(valores, columns=cols)
df
因此,来自上一级的每个帐户都将来自下一级的帐户相加
我想创建包含每个级别的帐户组名称的列,该列获取帐户的级别以及该帐户组的最终级别。为清楚起见,我希望得到以下输出:
我尝试了以下方法,但当我需要以某种方式读取前几行的值时,我被卡住了,并且在其中一个步骤(FutureWarning: Columnar iteration over characters will be deprecated in future releases.
)中出现了FutureWarning错误
df['sub_account_1'], df['sub_account_2'], df['sub_account_3'], df['sub_account_4']\
= df['account'].str.split('.').str
df['clasif_1'], df['clasif_2'], df['clasif_3'], df['clasif_4'] = ("", "", "", "")
def account_level(df):
if df['sub_account_2'] == '00':
return '2'
elif df['sub_account_3'] == '00':
return '3'
elif df['sub_account_4'] == '00':
return '4'
else:
return np.nan
df['nivel_cuenta'] = df.apply(account_level, axis = 1)
停在那里。我相信必须有一种更聪明的方法来解决这个问题,也许一种已知的方法可以解决这个问题,因为这种情况并不罕见(账户和子账户级别)
真实案例场景最多有8个子级别,但帐户代码具有相同的结构。我将使用创建的列来控制原始数据集中给出的小计,然后进行一些分析
有人能给我指出正确的方向吗?(我不想回到Excel中来解决这个问题……)
您可以循环数据帧行,并应用sub_account_x==0上的条件来填充所需的列
结果:
我终于能够用下面的代码做我需要的事情了。我主要使用一些python进行循环,但我仍然觉得必须有一种更“熊猫”的方式来实现这一点。基于其他stackoverflow问题,我尝试了几种方法,但在其他方面很难做到这一点。我将把代码留在这里,但我们非常感谢您的反馈,欢迎您提出更多想法
输出:
相关问题 更多 >
编程相关推荐