I am starting to learn Pandas, and I was following the question here and could not get the solution proposed to work for me and I get an indexing error. This is what I have
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())
which outputs the following (I am using 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
Then, I try to append the cumulative number calculation under the label "new" as suggested in the post
df["new"] = df.groupby("L1", as_index=False).apply(lambda x : pd.expanding_sum(x.sort("L3", ascending=False)["L3"])/x["L3"].sum())
I get this:
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
Does anybody knows what the problem is? How can I reinsert the calculated value into the dataframe so it shows the values in order (descending by "new" for each label X, Y, Z.)
pandasare you using? The above seems to work for me. - DSM