【问题标题】:Modifying Arrays to change the column values of a pandas dataframe Python修改数组以更改熊猫数据框 Python 的列值
【发布时间】:2026-01-19 18:35:02
【问题描述】:

我想修改values,使其自身反转,从而产生下面的预期输出。我怎样才能得到它?

代码:

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:']
diction = dict(zip(capinc_variables, np.transpose(values.reshape((-1, 7)))))
display(pd.DataFrame(diction, index=Timeframes))

输出:

预期输出:

【问题讨论】:

    标签: python arrays pandas database numpy


    【解决方案1】:

    90% loss 添加到列表capinc_variables 并简化DataFrame - 通过索引[::-1] 来获得正确的订单交换排序:

    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','90% loss','liquidations']
    Timeframes = ['Entirety:', 'Last Month:', 'Three Months:', 'Six Months:', 'Last Year:', 'Last Two Years:']
    

    df = pd.DataFrame(values[::-1].reshape(-1, 7), index=Timeframes, columns=capinc_variables)
    print (df)
                     10% loss  25% loss  50% loss  65% loss  75% loss  90% loss  \
    Entirety:           713.0     284.0     141.0      95.0      36.0      10.0   
    Last Month:           5.0       2.0       0.0       0.0       0.0       0.0   
    Three Months:         5.0       2.0       0.0       0.0       0.0       0.0   
    Six Months:          64.0      59.0      34.0      24.0       8.0       0.0   
    Last Year:          292.0     193.0     110.0      66.0      14.0       0.0   
    Last Two Years:     568.0     245.0     110.0      66.0      14.0       0.0   
    
                     liquidations  
    Entirety:                 0.0  
    Last Month:               0.0  
    Three Months:             0.0  
    Six Months:               0.0  
    Last Year:                0.0  
    Last Two Years:           0.0  
    

    【讨论】: