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

标签 python pandas

我在大型数据帧上使用 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/

相关文章:

pandas - 编辑 Pandas 数据透视表

python - 比较 Pandas 中的日期范围

python - Pandas read_csv 在 NFS 上 super 慢

python - Alexa 技能 : Get user location

python - 从 pd.read_sql 输出附加到 Pandas Dataframe

python - 如何检索 Pandas 中所有有错误的行

python - 按事件进行时间序列标准化 - 通用版本

python networkx 在某些条件下删除节点和边

python - 将程序作为可执行文件运行时设置默认 python 版本 ./xxx.py - 在 linux 上

python - 将多索引 pandas 连接成单个 pandas