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

如何反转numpy数组values以调整pandas DataFrame的输出列值

你可以通过反转reshape后数组的行顺序来实现需求,只需要修改构造diction的一行代码即可,修改后的完整代码如下:

import numpy as np
import pandas as pd

values = np.array([0.0, 0.0, 14.0, 66.0, 110.0, 245.0, 568.0, 0.0, 0.0, 14.0, 66.0, 110.0, 193.0, 292.0, 
           0.0, 0.0, 8.0, 24.0, 34.0, 59.0, 64.0, 0.0, 0.0, 0.0, 0.0, 0.0, 2.0, 5.0, 0.0, 0.0, 0.0,
           0.0, 0.0, 2.0, 5.0, 0.0, 10.0, 36.0, 95.0, 141.0, 284.0, 713.0])
capinc_variables = ['10% loss', '25% loss', '50% loss', '65% loss','75% loss','liquidations']
Timeframes = ['Entirety:', 'Last Month:', 'Three Months:', 'Six Months:', 'Last Year:', 'Last Two Years:']
# 仅修改了这一行,在reshape后加[::-1]反转行顺序
diction = dict(zip(capinc_variables, np.transpose(values.reshape((-1, 7))[::-1])))
display(pd.DataFrame(diction, index=Timeframes))

实现原理

原代码中values.reshape((-1, 7))会得到一个6行7列的二维数组,行顺序和你需要展示的Timeframes顺序正好相反,我们使用numpy的切片语法[::-1]对行维度做反转后再转置,就能得到和预期顺序匹配的数据。

如果不想修改数组,也可以直接反转Timeframes列表实现同样的效果,对应修改代码为:

display(pd.DataFrame(diction, index=Timeframes[::-1]))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 15:36:00