我有一个这样的Pandas数据帧:
df = pd.DataFrame({'id': [121, 34324, 111, 12, 45, 232],
'weight': [10, 2, 80, 49, 71, 18],
'var_bool': [True, True, False, True, False, True],
'var_cat': ['red', 'blue', 'red', 'green', 'green', 'blue']})
df['var_bool'] = df['var_bool'].astype('bool')
df['var_cat'] = df['var_cat'].astype(pd.api.types.CategoricalDtype())我想应用一个函数来计算唯一标签的出现频率,其权重由" weight“列给出:
df['var_bool'].value_counts() #I need to consider the weight of each row
df['var_cat'].value_counts() #I need to consider the weight of each row该函数必须同时适用于"var_bool“和"var_cat",可能需要使用快速引擎(数据帧相当大)。非常感谢!
编辑:结果应该是:
#for "var_bool"
True 79
False 151
#for "var_cat"
red 90
blue 20
green 120发布于 2019-12-19 00:12:43
我不认为没有groupby就能做到这一点。
df.groupby('var_bool')['weight'].sum()https://stackoverflow.com/questions/59395950
复制相似问题