簡體   English   中英

是否有 function 用於獲取每個組中 dataframe 中唯一值的數量?

[英]Is there a function for getting the number of unique values in the dataframe in each group?

我有一個 dataframe 有兩列:label 和值。 我想確定每個 label 組中出現的 dataframe 中唯一值的數量。

例如,給定以下 dataframe:

test_df = pd.DataFrame({
    'label': [1, 1, 1, 1, 2, 2, 3, 3, 3], 
    'value': [0, 0, 1, 2, 1, 2, 2, 3, 4]})
test_df
  label     value
0   1         0
1   1         0
2   1         1
3   1         2
4   2         1
5   2         2
6   3         2
7   3         3
8   3         4

預期的 output 為:

  label     uni_val
0   1         1 -> {0} is unique value for this label compared to other labels
1   2         0 -> no unique values for this label compared to other labels
2   3         2 -> {3, 4} are unique values for this label compared to other labels

一種方法是獲取每個 label 的唯一值,然后計算它們在所有元素中的非重復值。

test_df.groupby('label')['value'].unique()

label
1    [0, 1, 2]
2       [1, 2]
3    [2, 3, 4]
Name: value, dtype: object

有沒有更高效、更簡單的方法?

您可以在['label', 'value']上刪除重復項,然后在value上刪除重復項:

(test_df.drop_duplicates(['label','value'])         # remove duplicates on pair (label, value)
    .drop_duplicates('value', keep=False)           # only keep unique `value`
    .groupby('label')['value'].count()              # count as usual
    .reindex(test_df.label.unique(), fill_value=0)  # fill missing labels with 0
)

Output:

label
1    1
2    0
3    2
Name: value, dtype: int64

暫無
暫無

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

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