熊猫 - 索引类型值的变化

时间:2016-11-04 15:51:34

标签: python pandas

我正在使用multiIndex Panda DataFrames。我的索引的值被报告为字符串 - 但是,我需要将它们更改为整数或浮点数,然后再用它们进行一些计算。 有没有一种有效的方法来做到这一点(最好没有for循环,因为那些耗费了大量的计算时间)?

import pandas as pd
import numpy as np

idx = pd.IndexSlice
ix = pd.MultiIndex.from_product(
    [['2015', '2016', '2017', '2018'],
     ['2016', '2017', '2018', '2019', '2020'],
     ['A', 'B', 'C']],
    names=['SimulationStart', 'ProjectionPeriod', 'Group']
)

df = pd.DataFrame(np.random.randn(60, 1), index=ix, columns=['Origin'])
origin = df.loc[idx[:, :, :], 'Origin'].values


get_index_values = df.index.get_level_values
projection = get_index_values('ProjectionPeriod')

# This function fails - is there an easy solution for this 
# (preferably without accessing each item at a time in a for loops)?
int(projection)

1 个答案:

答案 0 :(得分:1)

使用astype转换Error: cannot call methods on dialog prior to initialization; attempted to call method 'moveToTop'set_levels以设置特定的索引级别值:

dtype