是否有一个函数可以获取每个组中数据框中唯一值的数量?

问题描述 投票:1回答:1

我有一个包含两列的数据框:标签和值。我想确定每个标签组中出现的数据框中唯一值的数量。

例如,给定以下数据框:

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

预期输出是:

  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

一种方法是获取每个标签的唯一值,然后计算所有元素中它们的非重复值。

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

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

有没有更有效,更简单的方法?

python pandas pandas-groupby
1个回答
1
投票

您可以在['label', 'value']上放置重复项,然后在value上放置重复项:

(test_df.drop_duplicates(['label','value'])
    .drop_duplicates('value', keep=False)
    .groupby('label')['value'].nunique()
    .reindex(test_df.label.unique(), fill_value=0)
)

输出:

label
1    1
2    0
3    2
Name: value, dtype: int64
© www.soinside.com 2019 - 2024. All rights reserved.