gpt4 book ai didi

python - 按组每列的唯一值数

转载 作者:太空狗 更新时间:2023-10-29 22:22:17 25 4
gpt4 key购买 nike

考虑以下数据框:

      A      B  E
0 bar one 1
1 bar three 1
2 flux six 1
3 flux three 2
4 foo five 2
5 foo one 1
6 foo two 1
7 foo two 2

我想为 A 的每个值查找其他列中唯一值的数量。

  1. 我认为以下内容可以做到这一点:

    df.groupby('A').apply(lambda x: x.nunique())

    但是我得到一个错误:

    AttributeError: 'DataFrame' object has no attribute 'nunique'
  2. 我也试过:

    df.groupby('A').nunique()

    但我也得到了错误:

    AttributeError: 'DataFrameGroupBy' object has no attribute 'nunique'
  3. 最后我尝试了:

    df.groupby('A').apply(lambda x: x.apply(lambda y: y.nunique()))

    返回:

          A  B  E
    A
    bar 1 2 1
    flux 1 2 2
    foo 1 3 2

    似乎是正确的。奇怪的是,它还在结果中返回列 A。为什么?

最佳答案

DataFrame 对象没有nunique,只有Series 有。您必须选择要应用 nunique() 的列。您可以使用简单的点运算符执行此操作:

df.groupby('A').apply(lambda x: x.B.nunique())

将打印:

A
bar 2
flux 2
foo 3

并做:

df.groupby('A').apply(lambda x: x.E.nunique())

将打印:

A
bar 1
flux 2
foo 2

或者,您可以使用一个函数调用来完成此操作:

df.groupby('A').aggregate({'B': lambda x: x.nunique(), 'E': lambda x: x.nunique()})

将打印:

      B  E
A
bar 2 1
flux 2 2
foo 3 2

要回答关于为什么递归 lambda 也打印 A 列的问题,这是因为当您执行 groupby/apply 操作时,您现在正在遍历三个 DataFrame 对象。每个 DataFrame 对象都是原始对象的子 DataFrame。对其应用操作会将其应用于每个 Series。每个要应用 nunique() 运算符的 DataFrame 有三个 Series

在每个 DataFrame 上评估的第一个 SeriesA Series,因为你已经完成了A上的groupby,你知道在每个DataFrame中,A中只有一个唯一值 系列。这解释了为什么您最终得到一个包含所有 1A 结果列。

关于python - 按组每列的唯一值数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27002926/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com