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

如何统计CSV文件中第一列数值的首位数字出现次数

嘿,这个需求很清晰,我给你两种实用的实现方案,分别用基础的Python标准库和更简洁的pandas库来搞定!

解决方案:统计CSV中数值的首位数字出现次数

方法一:使用Python标准库(无需额外安装)

如果不想安装第三方库,用Python自带的csv和collections模块就能完成,代码逻辑清晰,适合新手理解:

import csv
from collections import defaultdict

# 初始化统计字典,自动把1-9的数字计数初始化为0
digit_counts = defaultdict(int)

# 替换成你的CSV文件路径
csv_file_path = "your_data.csv"

with open(csv_file_path, 'r', encoding='utf-8') as file:
    csv_reader = csv.reader(file)
    # 跳过第一行的表头"Values"
    next(csv_reader)
    
    for row in csv_reader:
        # 跳过空行或第一列无内容的行
        if not row[0].strip():
            continue
        
        try:
            # 处理可能的小数、负数:先转成数值取绝对值,再转字符串提取首位
            num = float(row[0].strip())
            if num == 0:
                continue  # 0没有1-9的首位数字,直接跳过
            first_digit = int(str(abs(num))[0])
            # 只统计1-9的数字
            if 1 <= first_digit <= 9:
                digit_counts[first_digit] += 1
        except ValueError:
            # 遇到非数值内容时跳过该行
            continue

# 按数字顺序输出统计结果
print("首位数字出现次数统计:")
for digit in sorted(digit_counts.keys()):
    print(f"首位为{digit}的数值有{digit_counts[digit]}个")

方法二:使用pandas库(更简洁高效)

如果经常处理CSV数据,pandas能大幅简化代码,运行效率也更高,先确保你已经安装了pandas(pip install pandas):

import pandas as pd

# 替换成你的CSV文件路径
csv_file_path = "your_data.csv"

# 读取CSV,只取第一列,指定表头为"Values"
df = pd.read_csv(csv_file_path, usecols=[0], header=0, names=["Values"])

# 提取首位数字:转字符串取第一个字符,处理负数/小数时先取绝对值
df["First_Digit"] = df["Values"].apply(lambda x: int(str(abs(float(x)))[0]))

# 过滤出1-9的数字,统计每个数字的出现次数并按顺序排序
digit_counts = df[df["First_Digit"].between(1, 9)]["First_Digit"].value_counts().sort_index()

# 输出结果
print("首位数字出现次数统计:")
for digit, count in digit_counts.items():
    print(f"首位为{digit}的数值有{count}个")

额外说明

  • 两种方案都能处理小数(比如123.45的首位是1)和负数(比如-900的首位是9),如果你的数据里没有这些情况,可以去掉绝对值和转浮点数的逻辑,直接处理字符串即可。
  • 如果CSV里有非数值的无效行,代码会自动跳过,不会报错中断运行。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 03:39:27