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

获取Pandas DataFrame列中各值类型的数量及占比

Pandas DataFrame列值类型统计与占比计算

原始数据

给定的DataFrame定义如下:

import pandas as pd

data = {
    "A": [420, 380.2, 390.5, "alpha", "beta", "gamma"],
    "B": [520.30, 380.2, 390.5, 885.07, 56.3, 45.2],
}
df = pd.DataFrame(data)

需求说明

  • 对列A拆分统计各值类型的数量及占比(如int、float、string类型的数量和各自占比)
  • 验证列B的值类型占比是否为100% float

解决方案

1. 统计列A的类型数量与占比

通过apply(type)获取每个元素的类型,结合value_counts()统计数量后计算占比:

# 获取列A每个元素的类型
a_types = df["A"].apply(type)

# 统计各类型的数量并重命名索引为易读类型名
type_counts = a_types.value_counts()
type_counts.index = type_counts.index.map(lambda x: x.__name__)

# 计算各类型占比(保留两位小数)
type_ratios = (type_counts / len(df["A"])).mul(100).round(2)

# 合并数量和占比结果
a_type_stats = pd.DataFrame({"数量": type_counts, "占比(%)": type_ratios})
print("列A的类型统计结果:")
print(a_type_stats)

运行结果示例:

数量  占比(%)
str     3   50.00
float   2   33.33
int     1   16.67

2. 验证列B的类型占比

用相同逻辑验证列B的类型分布:

# 获取列B每个元素的类型
b_types = df["B"].apply(type)

# 统计类型数量与占比
b_type_counts = b_types.value_counts()
b_type_counts.index = b_type_counts.index.map(lambda x: x.__name__)
b_type_ratios = (b_type_counts / len(df["B"])).mul(100).round(2)

b_type_stats = pd.DataFrame({"数量": b_type_counts, "占比(%)": b_type_ratios})
print("\n列B的类型统计结果:")
print(b_type_stats)

运行结果示例:

数量  占比(%)
float   6  100.00

可确认列B的所有值均为float类型,占比100%。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 15:15:10