Python Pandas - 返回一個包含從索引物件中唯一值計數的序列,同時考慮 NaN 值


使用 index.value_counts() 方法返回一個包含從索引物件中唯一值計數的序列,同時考慮 NaN 值。將引數 dropna 設定為值 False

首先匯入所需的庫 -

import pandas as pd
import numpy as np

建立一個帶有一些 NaN 值的 Pandas 索引 −

index = pd.Index([50, 10, 70, np.nan, 90, 50, np.nan, np.nan, 30])

顯示 Pandas 索引 −

print("Pandas Index...\n",index)

使用 value_counts() 計數唯一值。使用“dropna”引數的“False”值同時考慮 NaN −

index.value_counts(dropna=False)

示例

以下是程式碼 −

import pandas as pd
import numpy as np

# Creating Pandas index with some NaN values as well
index = pd.Index([50, 10, 70, np.nan, 90, 50, np.nan, np.nan, 30])

# Display the Pandas index
print("Pandas Index...\n",index)

# Return the number of elements in the Index
print("\nNumber of elements in the index...\n",index.size)

# Return the dtype of the data
print("\nThe dtype object...\n",index.dtype)

# count of unique values using value_counts()
# considering NaN as well using the "False" value of the "dropna" parameter
print("\nGet the count of unique values with NaN...\n",index.value_counts(dropna=False))

輸出

這將產生以下輸出 −

Pandas Index...
Float64Index([50.0, 10.0, 70.0, nan, 90.0, 50.0, nan, nan, 30.0], dtype='float64')

Number of elements in the index...
9

The dtype object...
float64

Get the count of unique values with NaN...
NaN   3
50.0  2
10.0  1
70.0  1
90.0  1
30.0  1
dtype: int64

更新於: 2021 年 10 月 13 日

142 次檢視

開啟你的職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.