Python 新列的多索引计算
我有一个这样的数据帧Python 新列的多索引计算,python,pandas,Python,Pandas,我有一个这样的数据帧 status new allocation asset csh fi eq csh fi eq person act_type p1 inv 0.0 0.0 100000.0
status new allocation
asset csh fi eq csh fi eq
person act_type
p1 inv 0.0 0.0 100000.0 0.0 0.0 1.0
rsp 0.0 30000.0 20000.0 0.0 0.6 0.4
tfsa 10000.0 40000.0 0.0 0.2 0.8 0.0
右三列是每种act_类型的总百分比。以下内容不能正确计算列:
# set the percent allocations
df.loc[idx[:,:],idx["allocation",'csh']] = df.loc[idx[:,:],idx["new",'csh']] / df.loc[idx[:,:],idx["new",:]].sum(axis=1)
df.loc[idx[:,:],idx["allocation",'fi']] = df.loc[idx[:,:],idx["new",'fi']] / df.loc[idx[:,:],idx["new",:]].sum(axis=1)
df.loc[idx[:,:],idx["allocation",'eq']] = df.loc[idx[:,:],idx["new",'eq']] / df.loc[idx[:,:],idx["new",:]].sum(axis=1)
我尝试在一行上结合“csh”、“fi”、“eq”进行这些计算,如下所示:
df.loc[idx[:,:],idx["new", ('csh', 'fi', 'eq')]] / df.loc[idx[:,:],idx["new",:]].sum(axis=1)
但这会导致ValueError:无法在未指定级别和名称重叠的情况下联接
如何将这三行代码减少为一行代码,以便我将('csh'、'fi'、'eq')除以账户总额,并在下一列中获得百分比,有什么建议吗?首先
idx[:,:]
应简化为:
,然后使用axis=0
对新列使用重命名
:
你是最棒的。谢谢
df1=df.loc[:, idx["new",('csh', 'fi', 'eq')]].div(df.loc[:, idx["new",:]].sum(axis=1),axis=0)
df = df.join(df1.rename(columns={'new':'allocation'}, level=0))
print (df)
status new allocation
asset csh fi eq csh fi eq
person act_type
p1 inv 0.0 0.0 100000.0 0.0 0.0 1.0
rsp 0.0 30000.0 20000.0 0.0 0.6 0.4
tfsa 10000.0 40000.0 0.0 0.2 0.8 0.0