确定EXCel文件的格式,避免UTF-8的错误

import chardet
import pandas as pd

# 指定文件路径
file_path = "你的文件名.csv"

# 读取部分数据检测编码
def detect_encoding(file_path, sample_size=100000):
    with open(file_path, "rb") as f:
        rawdata = f.read(sample_size)  # 读取前100KB
        result = chardet.detect(rawdata)  # 检测编码
    return result["encoding"]

# 获取检测到的编码
detected_encoding = detect_encoding(file_path)
print(f"检测到的编码格式: {detected_encoding}")

# 使用检测到的编码读取 CSV 文件
try:
    df = pd.read_csv(file_path, encoding=detected_encoding)
    print("文件读取成功!")
except Exception as e:
    print(f"读取 CSV 文件时出错: {e}")

# 显示数据前几行
print(df.head())

确定好文件格式以后,选择相对于的格式来读取文件,避免UTF-8的错误

# 上传文件
file_path = "water_quality_data_with_dates.csv"

# 读取数据,使用检测到的GB2312编码(仅做一个例子)
df = pd.read_csv(file_path, encoding="GB2312")

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值