我正在尋找一種方法來總結給定列中的值 > 或 < 某個閾值(此處為 days_install_to_event 列中的 > 6)。
我嘗試了許多不同的方法,例如 loc、query 或 groupby,但它只回傳 > 6 的值而不是 < 6 的值。
這是我嘗試過的一些事情:
df = pd.DataFrame({
'custom_action' : ['First_puchase', 'First_puchase', 'First_puchase', 'First_puchase',
'First_puchase', 'First_puchase', 'First_puchase', 'First_puchase'],
'days_install_to_event' : [1, 2, 3, 4, 5, 6, 7, 8],
'number_unique_users' : [1350, 250, 13, 2, 1, 2, 1, 2]})
df
custom_action days_install_to_event number_unique_users
0 First_puchase 1 1350
1 First_puchase 2 250
2 First_puchase 3 13
3 First_puchase 4 2
4 First_puchase 5 1
5 First_puchase 6 2
6 First_puchase 7 1
7 First_puchase 8 2
8 First_puchase 9 3
9 First_puchase 10 2
df_1 = df.loc[df['days_install_to_event'] > 6].sum()
df_2 = df.query("days_install_to_event > 6")['number_unique_users'].sum()
df_1
df_2
輸出:
custom_action First_puchaseFirst_puchase
days_install_to_event 34
number_unique_users 8
8
期望的輸出:
custom_action days_install_to_event number_unique_users
0 First_puchase 1 1350
1 First_puchase 2 250
2 First_puchase 3 13
3 First_puchase 4 2
4 First_puchase 5 1
5 First_puchase 6 2
6 First_puchase 7 8
提前,很抱歉,如果有人問了一個非常相似的問題,我過去 2 天一直在四處尋找,但沒有找到與我正在尋找的完全匹配的東西。這可能是由于配方。
謝謝你的幫助 :)
uj5u.com熱心網友回復:
據我所知,沒有開箱即用的解決方案,但您可以通過創建幫助分組列來獲得此結果:
# Set days_install_to_event = 7 if the value is larger than 6
grouper = df['days_install_to_event'].mask(df['days_install_to_event'] > 6, '7 ')
然后,在本專欄的幫助下,您可以使用groupby.agg:
In [27]: df.groupby(grouper).agg({
'number_unique_users': 'sum',
'custom_action': 'first',
}).reset_index()
Out[27]:
days_install_to_event number_unique_users custom_action
0 1 1350 First_puchase
1 2 250 First_puchase
2 3 13 First_puchase
3 4 2 First_puchase
4 5 1 First_puchase
5 6 2 First_puchase
6 7 8 First_puchase
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/465169.html
標籤:python-3.x 熊猫
上一篇:在熊貓資料框中分組定期資料
