python - 按条件从不同列和索引获取值

标签 python python-3.x pandas pandas-groupby

给定代表用户事件的 df。

index   id  action_id   feature session_id  n_page duration
1       1    null       null    1_1         1      1
2       1    3          a       1_1         2      1
3       1    null               1_1         3      1
4       1    null       pay     1_1         4      1
5       1    24                 1_1         5      1
6       1    107                1_1         6      2
7       2    null               2_1         1      1
8       2    107        c       2_1         2      1
9       2    null               2_1         3      1
10      2    34         pay     2_1         4      1

我需要按 session_id 进行分组,并仅在 action_id == 34 或 24 且 n_page 值按 action_id 的 session 中,当操作 id == 3 或 107 时获取功能列的最后值

输出df:

session_id  n_page  feature sum_duration
1_1         5       a       7
2_1         4       c       4

最佳答案

df_group = df[["session_id", "sum_duration"]].groupby("session_id")["sum_duration"].sum().reset_index()

df_dup = df[(df["action_id"] == 3)| (df["action_id"] == 104)]["session_id","n_page","feature"]

df_dup.merge(df_group, on = "session_id", how = "inner" )

我们可以根据所需的输出更改连接条件。 如果这不能产生所需的输出,那么如果您提供用于创建输入数据的代码,那就太好了。

关于python - 按条件从不同列和索引获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57586586/

相关文章:

windows - 当我使用 pytesseract 和 CREATE_NO_WINDOW 运行 tesseract 时如何隐藏控制台窗口

python - 解包值过多时出现错误(预期2)

"with"语句的 Python 无效语法

python - 如何在管道内使用 SMOTENC(错误 : Some of the categorical indices are out of range)?

python - 如何在 GAE Python NDB 中获取最新数据

python - 为什么我需要 Selenium 中的 ChromeDriver?

python - 如何将 Dask Dataframe 转换为 Dask Array?

python - Pandas DataFrame 列数值积分

python - 从python获取java版本号

python - 如何在运行时复制 python 模块?