簡體   English   中英

Pandas groupby std 返回一個空的 dataframe

[英]Pandas groupby std returning an empty dataframe

我有一個 pandas dataframe 具有以下感興趣的列 - 產品代碼和價格。 我想查看具有相同代碼的產品的標准偏差。

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

如您所見,大多數產品代碼只出現一次。 當我運行 describe 時,諸如 std、mean 等指標由於某種原因沒有出現。

當我特別要求運行標准偏差時,我得到以下信息

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

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

經歷了我的錯誤很多次,顯然錯誤是當我使用 to_numeric 時,無論是引發錯誤還是強制錯誤,它實際上並沒有改變列的數據類型,它仍然被歸類為 object。 使用

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

能夠解決這個問題。 這也是為什么當我嘗試使用 describe() 方法時,它只會列出適用於分類變量的指標。 我非常感謝您@Laurent 和@jezrael 的回答!

如果使用errors='raise'如果有非數字值,則返回相同的輸出,而不是數字。

需要:

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

因此,給定以下玩具 dataframe:

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

暫無
暫無

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

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