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

如何用Python或Pandas处理URL读取的CSV中空字符串替换为另一列值?

用Python或Pandas实现CSV空值替换(同行另一列填充)

需求说明:

  • 从URL读取CSV文件,提取指定两列输出
  • 核心要求:当目标列单元格为空字符串('')时,用同一行另一列的值替代该空值
    现有代码(基于numpy):
data = requests.get(url)
lines = data.text.splitlines()
reader = np.loadtxt(url, dtype=str, delimiter=';', skiprows=1, usecols=(0, 3))

for row in reader:
    print(row)

示例问题行:['22709' ''](第二列为空,需要用第一列的22709填充)


方案1:纯Python(结合csv模块)

无需依赖第三方数据处理库,适合轻量场景:

import requests
import csv

url = "你的CSV文件URL"
response = requests.get(url)
# 按行解析CSV,指定分隔符为分号
csv_reader = csv.reader(response.text.splitlines(), delimiter=';')
# 跳过表头行
next(csv_reader)

for row in csv_reader:
    # 提取目标两列(索引0和3)
    col0 = row[0]
    col3 = row[3]
    # 空值替换逻辑
    processed_col3 = col0 if col3 == '' else col3
    # 输出处理后的结果
    print([col0, processed_col3])

方案2:Pandas实现(高效批量处理)

适合大文件或复杂数据清洗场景,代码更简洁:

import pandas as pd
import numpy as np

url = "你的CSV文件URL"
# 直接从URL读取指定列,跳过表头
df = pd.read_csv(
    url,
    sep=';',
    skiprows=1,
    usecols=[0, 3],
    header=None,
    dtype=str  # 强制保持字符串类型,避免自动类型转换
)

# 给列命名(可选,方便后续操作)
df.columns = ['col0', 'col3']

# 空值替换:先将空字符串转为NaN,再用同行col0的值填充
df['col3'] = df['col3'].replace('', np.nan).fillna(df['col0'])

# 输出处理结果
print(df)
# 若要输出数组格式,可转换为numpy数组
# print(df.to_numpy())

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 13:35:18