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

Python pandas代码求助:TGT股票数据子集提取输出与预期不符

TGT股票数据处理代码问题排查

任务要求

  • 从target.csv加载TGT股票数据
  • 生成三个数据对象:
    • tgt_march:取数据框最后19天的数据
    • tgt_vol:提取Date和Volume列
    • tgt_close:提取Date和Close列
  • 输入3时,预期输出:

The volume of TGT on 2018-03-05 is 7654766. The closing stock price of TGT on 2018-03-05 is $75.14.

现有代码

import pandas as pd

tgt = pd.read_csv('target.csv')
df=tgt

tgt_march = df[-19:]

tgt_vol = df[['Date', 'Volume']]
tgt_close = df[ ['Date', 'Close']]

day = int(input()) - 1

volume_row = tgt_vol.iloc[[day]]
volume = volume_row.iloc[0][1]

close_row = tgt_close.iloc[[day]]
close = close_row.iloc[0][1]

date = tgt_march.iloc[[day]].iloc[0][0]

print("The volume of TGT on " + str(date) + " is " + str(int(volume)) + ".")
print("The closing stock price of TGT on " + str(date) + " is $" + str(close) + ".")

实际输出(输入3时)

The volume of TGT on 2018-03-05 is 94400.
The closing stock price of TGT on 2018-03-05 is $69.75.

问题原因与修正方案

核心错误

你从全量原始数据的tgt_vol、tgt_close中提取成交量和收盘价,但日期却是从tgt_march(最后19天子集)中获取的,两者的索引完全不对应。比如输入3对应day=2,你取的是原始数据第3行的成交量/收盘价,而非tgt_march第3行的对应数据,导致输出和预期不符。

修正方式一:直接从tgt_march取数(简洁版)

不需要单独创建tgt_vol和tgt_close,直接从目标子集里提取对应行的所有字段:

import pandas as pd

df = pd.read_csv('target.csv')
tgt_march = df[-19:]

day = int(input()) - 1
selected_row = tgt_march.iloc[day]

date = selected_row['Date']
volume = int(selected_row['Volume'])
close = selected_row['Close']

print(f"The volume of TGT on {date} is {volume}.")
print(f"The closing stock price of TGT on {date} is ${close}.")

修正方式二:保留指定变量的写法

如果必须保留tgt_vol和tgt_close这两个变量,要确保它们是从tgt_march衍生的,而非原始数据:

import pandas as pd

df = pd.read_csv('target.csv')
tgt_march = df[-19:]

# 从tgt_march而非原始df提取列
tgt_vol = tgt_march[['Date', 'Volume']]
tgt_close = tgt_march[['Date', 'Close']]

day = int(input()) - 1

volume = tgt_vol.iloc[day]['Volume']
close = tgt_close.iloc[day]['Close']
date = tgt_march.iloc[day]['Date']

print(f"The volume of TGT on {date} is {int(volume)}.")
print(f"The closing stock price of TGT on {date} is ${close}.")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 21:15:36