簡體   English   中英

如何過濾和分組 pandas DataFrame 以獲得兩列組合的計數

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

很抱歉,我無法以簡潔的方式將整個問題放在標題中。 原諒我的英語。 我將用一個例子來解釋我的問題。

假設我有這個數據集:

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"])

我想對每個Nameslot組合進行計數,但忽略同一 ID 的多個時間序列值。 例如,如果我只是按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

但是,對於ID == 0name == 1slot == 2有兩種組合,所以我希望計數為2而不是3

這是我理想中想要的桌子。

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

我試過了:

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")

但這給了我:

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

如果我刪除ID的重復項,它也不起作用。

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

印刷:

  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