我开始学习熊猫了,我正在关注这个问题 这里 并且无法让解决方案为我工作,我得到一个索引错误。这就是我所拥有的
from pandas import *
import pandas as pd
d = {'L1' : Series(['X','X','Z','X','Z','Y','Z','Y','Y',]),
'L2' : Series([1,2,1,3,2,1,3,2,3]),
'L3' : Series([50,100,15,200,10,1,20,10,100])}
df = DataFrame(d)
df.groupby('L1', as_index=False).apply(lambda x : pd.expanding_sum(x.sort('L3', ascending=False)['L3'])/x['L3'].sum())
输出以下内容(我正在使用iPython)
L1
X 3 0.571429
1 0.857143
0 1.000000
Y 8 0.900901
7 0.990991
5 1.000000
Z 6 0.444444
2 0.777778
4 1.000000
dtype: float64
然后,我尝试在帖子中建议的标签“new”下附加累积数字计算
df["new"] = df.groupby("L1", as_index=False).apply(lambda x : pd.expanding_sum(x.sort("L3", ascending=False)["L3"])/x["L3"].sum())
我明白了:
2196 value = value.reindex(self.index).values
2197 except:
-> 2198 raise TypeError('incompatible index of inserted column '
2199 'with frame index')
2200
TypeError: incompatible index of inserted column with frame index
有谁知道问题是什么?如何将计算的值重新插入到数据框中,以便按顺序显示值(对于每个标签X,Y,Z,以“new”降序)