簡體   English   中英

Pandas,根據一列中的唯一值和另一列中的 grouby 篩選 dataframe

[英]Pandas, filter dataframe based on unique values in one column and grouby in another

我有一個這樣的 dataframe:

ID  Packet Type

    1   1    A
    2   1    B
    3   2    A
    4   2    C
    5   2    B
    6   3    A
    7   3    C
    8   4    C
    9   4    B
   10   5    B
   11   6    C
   12   6    B
   13   6    A
   14   7    A

我想過濾 dataframe 以便我只有屬於大小為 n 的數據包的一部分並且類型都不同的條目。 只有 n 種類型。 對於此示例,我們使用 n=3 和類型 A、B、C。

最后我想要這個:

ID  Packet Type

    3   2    A
    4   2    C
    5   2    B
   11   6    C
   12   6    B
   13   6    A

我如何使用 pandas 執行此操作?

您可以使用nunique進行transform

out = df[df.groupby('Packet')['Type'].transform('nunique')==3]
Out[46]: 
    ID  Packet Type
2    3       2    A
3    4       2    C
4    5       2    B
10  11       6    C
11  12       6    B
12  13       6    A

另一種解決方案,使用.groupby + .filter

df = df.groupby("Packet").filter(lambda x: len(x) == x["Type"].nunique() == 3)

print(df)

印刷:

    ID  Packet Type
2    3       2    A
3    4       2    C
4    5       2    B
10  11       6    C
11  12       6    B
12  13       6    A

我將通過 object 遍歷 groupby,過濾並連接:

>>> pd.concat(frame for _,frame in df.groupby("Packet") if len(frame) == 3 and frame.Type.is_unique)
    ID  Packet Type
2    3       2    A
3    4       2    C
4    5       2    B
10  11       6    C
11  12       6    B
12  13       6    A

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM