Pandas groupby std 返回空数据框

Pandas groupby std returning an empty dataframe

我有一个 pandas 数据框,其中包含感兴趣的以下列 - 产品代码和价格。我想查看具有相同代码的产品的标准偏差。

df.price = pd.to_numeric(df.price, errors='raise')

len(df[df.price.isna()])
Out: 0

df.groupby(['productcode'])['price'].describe()

    count   unique  top freq
productcode             

T1H5T   1   1   38  1
T1J0T   1   1   11  1
T1L6E   1   1   24  1
T1H0G9  1   1   69  1

如您所见,大多数产品代码只出现一次。当我 运行 描述时,由于某些原因没有出现诸如 std、mean 和其他指标。

当我特别要求标准偏差为运行时,我得到以下

df.groupby(['productcode'])['price'].std(ddof=0)
Out: _

df[['productcode', 'price']].groupby(['productcode']).mean()
Out: DataError: No numeric types to aggregate

因此,给定以下玩具数据框:

import pandas as pd

df = pd.DataFrame(
    {
        "productcode": {
            0: "T1H 4K3",
            1: "T1H6X",
            2: "T1H4K",
            3: "T1H4K",
            4: "T1H6X",
            5: "T1H 4K3",
        },
        "price": {0: "47", 1: "28", 2: "47", 3: "25", 4: "19", 5: "47"},
    }
)
print(df)
# Outputs
  productcode price
0     T1H 4K3    47
1       T1H6X    28
2       T1H4K    47
3       T1H4K    25
4       T1H6X    19
5     T1H 4K3    47

您可以像这样获得具有相同代码的产品的标准差:

print(df.groupby("productcode").std())
# Outputs
                 price
productcode
T1H 4K3       0.000000
T1H4K        15.556349
T1H6X         6.363961

经历了我的错误很多次,显然错误是当我使用 to_numeric 时,无论是引发错误还是强制错误,它实际上并没有改变列的数据类型,它仍然被归类为对象。使用

df.price = df.price.astype(float)

能够解决该问题。这也是为什么当我尝试使用 describe() 方法时,它只会列出适用于分类变量的指标。非常感谢您@Laurent 和@jezrael 的回答!