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

Pandas调整DataFrame行顺序时遇TypeError错误,求解决方案

解决DataFrame调整行顺序时的TypeError错误

错误根源

你代码里的global_fx = global_fx.reset_index少加了括号,reset_index是pandas的方法,必须加()调用才会返回处理后的DataFrame。没加括号的话,global_fx就变成了方法对象,不是DataFrame,自然没法执行global_fx['Country'] = ...的赋值操作,这就是报错的核心原因。

修正后的代码

把那行改成global_fx = global_fx.reset_index(),同时修正之前的拼写错误(Switzerlanter→Switzerland),完整代码如下:

import pandas as pd
import numpy as np 

combined_global_fx_currencies = r'x:\xxx\xxx\xxxxx\xxxxx\xxxxxx.xlsx'
global_fx = pd.read_excel(combined_global_fx_currencies)

# 初始化Country列,修正拼写错误
global_fx['Country'] = ['United States', 'China', 'Euro Zone', 'Japan', 'United Kingdom', 'Australia', 'New Zealand', 'Russia', 'Saudi Arabia', 'Brazil', 'Mexico', 'Canada', 'Switzerland']

global_fx = global_fx.set_index('Country')

# 转换为百分比格式
for col in ['3 Years', '1 Year', 'YTD', '1 Month', '1 Week', 'Daily']:
    global_fx[col] = global_fx[col] * 100

# 添加Germany行,复制Euro Zone的数据
global_fx.loc['Germany'] = global_fx.loc['Euro Zone']

# 关键修正:调用reset_index()方法
global_fx = global_fx.reset_index()

# 指定新的Country顺序
global_fx['Country'] = ['United States', 'China', 'Euro Zone', 'Germany', 'Japan', 'United Kingdom', 'Australia', 'New Zealand', 'Russia', 'Saudi Arabia', 'Brazil', 'Mexico', 'Canada', 'Switzerland']

global_fx = global_fx.set_index('Country')

print(global_fx)

更简洁的优化方案

其实不用反复重置索引再赋值,直接用reindex方法指定想要的行顺序即可,步骤更少更直观:

import pandas as pd
import numpy as np 

combined_global_fx_currencies = r'x:\xxx\xxx\xxxxx\xxxxx\xxxxxx.xlsx'
global_fx = pd.read_excel(combined_global_fx_currencies)

global_fx['Country'] = ['United States', 'China', 'Euro Zone', 'Japan', 'United Kingdom', 'Australia', 'New Zealand', 'Russia', 'Saudi Arabia', 'Brazil', 'Mexico', 'Canada', 'Switzerland']
global_fx = global_fx.set_index('Country')

# 转换为百分比
for col in ['3 Years', '1 Year', 'YTD', '1 Month', '1 Week', 'Daily']:
    global_fx[col] *= 100

# 添加Germany行
global_fx.loc['Germany'] = global_fx.loc['Euro Zone']

# 直接用reindex指定目标行顺序
target_order = ['United States', 'China', 'Euro Zone', 'Germany', 'Japan', 'United Kingdom', 'Australia', 'New Zealand', 'Russia', 'Saudi Arabia', 'Brazil', 'Mexico', 'Canada', 'Switzerland']
global_fx = global_fx.reindex(target_order)

print(global_fx)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 21:42:47