You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Pandas中高效获取特定数据类型的value_counts?

如何高效获取Pandas中特定数据类型的value_counts

你遇到的KeyError是因为df.dtypes.value_counts()返回的Series索引是numpy dtype对象,不是字符串,直接用字符串索引自然会报错。完全不需要创建新DataFrame,下面两种方法更高效:

方法一:直接用对应的数据类型对象索引

直接通过numpy的dtype对象来索引结果Series,一步到位:

import pandas as pd
import numpy as np

df = pd.DataFrame(
    [['Bob', 20, 2],['Alice', 19, 3],['Joshua', 22, 1]],
    columns = ['Name', 'Age', 'Marks']
)

dtype_counts = df.dtypes.value_counts()
# 用numpy的int64类型对象索引
int64_count = dtype_counts[np.int64]
print("count int64: ", int64_count)

方法二:转换索引为字符串后用字符串索引

如果更习惯用字符串查询,先把Series的索引转为字符串类型,之后就能直接用字符串索引:

import pandas as pd

df = pd.DataFrame(
    [['Bob', 20, 2],['Alice', 19, 3],['Joshua', 22, 1]],
    columns = ['Name', 'Age', 'Marks']
)

dtype_counts = df.dtypes.value_counts()
# 将索引转换为字符串格式
dtype_counts.index = dtype_counts.index.astype(str)
# 直接用字符串索引
int64_count = dtype_counts['int64']
print("count int64: ", int64_count)

你之前创建新DataFrame的方法属于绕路操作,会额外增加内存开销和计算步骤,上面两种直接操作原Series的方法效率高得多。

内容的提问来源于stack exchange,提问作者Ramanathan Alamelu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.25 05:10:54