簡體   English   中英

熊貓 value_counts() + 重量

[英]Pandas value_counts() + weight

我有一個像這樣的 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())

我想應用一個函數來計算唯一標簽的頻率,權重由“權重”列給出:

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

我認為沒有 groupby 就無法做到這一點。

df.groupby('var_bool')['weight'].sum()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM