【发布时间】:2023-03-08 20:55:01
【问题描述】:
我有一个 df:
temp = pd.DataFrame({'Y': ['A', 'B', 'B', 'A', 'B'],
'Z': [10, 5, 6, np.nan, 12],
})
我将 Y 设置为索引,然后按组计算计数和大小:
temp.sort('Y', inplace=True)
temp.set_index('Y', inplace=True, drop=False)
temp.sort_index( inplace=True)
temp['n_obs'] = temp.groupby(by='Y')['Z'].transform('size')
temp['valid'] = temp.groupby(by='Y')['Z'].transform('count')
这会产生:
Y Z n_obs valid
Y
A A 10.0 2.0 1.0
A A NaN 2.0 1.0
B B 5.0 3.0 3.0
B B 6.0 3.0 3.0
B B 12.0 3.0 3.0
现在,我想将 valid 除以 n-obs 分组:
temp['New']=temp.groupby(by='Y').apply(lambda x: (x['valid'] / x['n_obs']))
但我收到此错误:
Exception: cannot handle a non-unique multi-index!
请解决?
【问题讨论】:
标签: python pandas indexing data-manipulation