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

使用Pandas DataFrame无法重命名表格列名的问题求助

问题:DataFrame列重命名失败

我是Jupyter Notebook和Python的新手,最近写代码时遇到问题:想把列名“Tesla Quarterly Revenue(Millions of US $)”和“Tesla Quarterly Revenue(Millions of US $).1”重命名为“Date”和“Revenue”,但操作后没有生效。

以下是我的代码:

!pip install pandas
!pip install requests
!pip install bs4
!pip install -U yfinance pandas 
!pip install plotly
!pip install html5lib
!pip install lxml
import yfinance as yf
import pandas as pd
import requests
from bs4 import BeautifulSoup
import plotly.graph_objects as go
from plotly.subplots import make_subplots
url = "https://www.macrotrends.net/stocks/charts/TSLA/tesla/revenue?utm_medium=Exinfluencer&utm_source=Exinfluencer&utm_content=000026UJ&utm_term=10006555&utm_id=NA-SkillsNetwork-Channel-SkillsNetworkCoursesIBMDeveloperSkillsNetworkPY0220ENSkillsNetwork23455606-2022-01-01"
html_data  = requests.get(url).text
soup = BeautifulSoup(html_data, 'html5lib')
tesla_revenue = pd.read_html(url, match = "Tesla Quarterly Revenue")[0]
tesla_revenue = tesla_revenue.rename(columns={"Tesla Quarterly Revenue(Millions of US $)":"Date","Tesla Quarterly Revenue(Millions of US $).1":"Revenue"})
tesla_revenue.head()

输出结果:
输出截图


解决方案

问题出在你写的列名和pandas实际读取到的列名不匹配——网页表格的列名可能带有隐藏的空格、换行符,或者pandas在解析时自动给列名加了额外格式,导致rename方法找不到对应列。

可以试试这两种更稳妥的方法:

方法1:直接赋值列名(最可靠)

如果你确定表格第一列是日期、第二列是收入,直接给columns属性赋值新名称:

tesla_revenue = pd.read_html(url, match = "Tesla Quarterly Revenue")[0]
# 直接替换列名
tesla_revenue.columns = ['Date', 'Revenue']
tesla_revenue.head()

方法2:先查看实际列名再调整

先打印当前DataFrame的列名,确认真实列名:

tesla_revenue = pd.read_html(url, match = "Tesla Quarterly Revenue")[0]
# 打印实际列名
print(tesla_revenue.columns)

根据打印出的真实列名,修改rename里的对应关系。如果列名前后有空格,先清理再重命名:

# 清理列名的多余空格
tesla_revenue.columns = tesla_revenue.columns.str.strip()
# 再执行重命名
tesla_revenue = tesla_revenue.rename(columns={"Tesla Quarterly Revenue(Millions of US $)":"Date","Tesla Quarterly Revenue(Millions of US $).1":"Revenue"})

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 21:40:50