我正在寻找一种方法来对给定列中的值 > 或 < 某个阈值进行求和(此处为 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 天我一直在四处寻找,但没有找到与我正在寻找的完全匹配的东西。这可能是由于配方。
感谢您的帮助:)
最佳答案
据我所知,没有开箱即用的解决方案,但您可以通过创建辅助石斑鱼列来获得此结果:
# 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
关于python-3.x - 根据条件求和值,如果不匹配则保留当前值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72016038/