简体   繁体   English

如何过滤和分组 pandas DataFrame 以获得两列组合的计数

[英]How to filter and group pandas DataFrame to get count for combination of two columns

I am sorry I could not fit the whole problem in the Title in a concise way.很抱歉,我无法以简洁的方式将整个问题放在标题中。 Pardon my English.原谅我的英语。 I will explain my problem with an example.我将用一个例子来解释我的问题。

Say I have this dataset:假设我有这个数据集:

dff = pd.DataFrame(np.array([["2020-11-13", 0, 3,4], ["2020-10-11", 1, 3,4], ["2020-11-13", 2, 1,4],
                             ["2020-11-14", 0, 3,4], ["2020-11-13", 1, 5,4], 
                             ["2020-11-14", 2, 2,4],["2020-11-12", 1, 1,4],["2020-11-14", 1, 2,4],["2020-11-15", 2, 5,4],
                             ["2020-11-11", 0, 1,2],["2020-11-15", 1, 1,2],
                             ["2020-11-18", 1, 2,4],["2020-11-17", 0, 1,2],["2020-11-20", 0, 3,4]]), columns=['Timestamp', 'ID', 'Name', "slot"])

I want to have a count for each Name and slot combination but disregard multiple timeseries value for same ID.我想对每个Nameslot组合进行计数,但忽略同一 ID 的多个时间序列值。 For example, if I simply group by Name and slot I get:例如,如果我只是按Nameslot分组,我会得到:

dff.groupby(['Name', "slot"]).Timestamp.count().reset_index(name="count")


  Name slot count
    1   2   3
    1   4   2
    2   4   3
    3   4   4
    5   4   2

However, for ID == 0 , there are two combinations for name == 1 and slot == 2 , so instead of 3 I want the count to be 2 .但是,对于ID == 0name == 1slot == 2有两种组合,所以我希望计数为2而不是3

This is the table I would ideally want.这是我理想中想要的桌子。

  Name slot count
    1   2   2
    1   4   2
    2   4   2
    3   4   2
    5   4   2

I tried:我试过了:

filter_one = dff.groupby(['ID']).Timestamp.transform(min)
dff1 = dff.loc[dff.Timestamp == filter_one]
dff1.groupby(['Name', "slot"]).Timestamp.count().reset_index(name="count")

But this gives me:但这给了我:

  Name slot count
    1   2   1
    1   4   1
    3   4   1

It also does not work if I drop duplicates for ID .如果我删除ID的重复项,它也不起作用。

x = dff.groupby(["Name", "slot"]).ID.nunique().reset_index(name="count")
print(x)

Prints:印刷:

  Name slot  count
0    1    2      2
1    1    4      2
2    2    4      2
3    3    4      2
4    5    4      2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM