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

如何使用Python从.csv文件中提取特定数据并存储至变量

Python 提取CSV汇率数据实现方案

前置准备

首先需要确认你CSV文件的列名、存储路径,以及你要提取的具体数据范围(特定列/特定行/指定货币对应的汇率)。

方案1:使用pandas库(推荐,适合新手操作表格数据)

1. 安装pandas

打开终端运行安装命令:
pip install pandas

2. 示例代码

假设你的CSV文件名为exchange_rates.csv,包含currency(货币名称)、rate(对应汇率)两列,示例结构如下:

currencyrate
USD7.24
EUR7.82
JPY0.051

代码实现:

import pandas as pd

# 读取CSV文件
df = pd.read_csv("exchange_rates.csv")

# 场景1:提取所有货币和汇率,存为字典(可直接通过货币名查汇率)
rate_dict = dict(zip(df["currency"], df["rate"]))
# 调用方式:rate_dict["USD"] 即可得到美元汇率

# 场景2:提取特定货币的汇率存入变量,比如美元汇率
usd_rate = df.loc[df["currency"] == "USD", "rate"].iloc[0]

# 场景3:提取指定列的所有值存入列表
currency_list = df["currency"].tolist()
rate_list = df["rate"].tolist()

注意事项

  • 替换代码中的列名currency、rate为你CSV文件实际的表头名称
  • 如果CSV文件和Python代码不在同一个文件夹,需要写文件的绝对路径,比如C:/Users/xxx/Downloads/exchange_rates.csv

方案2:使用Python内置csv模块(无需安装第三方库)

适合不想额外安装依赖的场景,代码示例:

import csv

rate_dict = {}
with open("exchange_rates.csv", "r", encoding="utf-8") as f:
    # 读取CSV,自动识别表头
    reader = csv.DictReader(f)
    for row in reader:
        currency = row["currency"]
        # 把汇率从字符串转为数字类型
        rate = float(row["rate"])
        rate_dict[currency] = rate

内容的提问来源于stack exchange,提问作者JL Delos Reyes

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 20:06:03