gpt4 book ai didi

python - 为什么 value_counts 不显示所有存在的值?

转载 作者:太空宇宙 更新时间:2023-11-04 10:09:58 26 4
gpt4 key购买 nike

我在大型数据帧上使用 pandas 0.18.1。我对 value_counts() 的行为感到困惑。这是我的代码:

print df.phase.value_counts()
def normalise_phase(x):
print x
return int(str(x).split('/')[0])
df['phase_normalised'] = df['phase'].apply(normalise_phase)

这将打印以下内容:

2      35092
3 26248
1 24646
4 22189
1/2 8295
2/3 4219
0 1829
dtype: int64
1
nan

两个问题:

  • 为什么 nan 打印为 normalise_phase 的输出,当 nan未在 value_counts 中列为值?
  • 为什么 value_countsdtype 显示为 int64 如果它具有如下字符串值1/2nan 也在里面吗?

最佳答案

您需要传递 dropna=False 才能计算 NaN(请参阅 docs)。int64 是系列的数据类型(值的计数)。值本身就是索引。如果您检查,索引的 dtype 将是对象。

ser = pd.Series([1, '1/2', '1/2', 3, np.nan, 5])

ser.value_counts(dropna=False)
Out:
1/2 2
5 1
3 1
1 1
NaN 1
dtype: int64

ser.value_counts(dropna=False).index
Out: Index(['1/2', 5, 3, 1, nan], dtype='object')

关于python - 为什么 value_counts 不显示所有存在的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38953532/

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