1
我正在使用multiIndex熊猫数据框。我的指数值以字符串形式报告 - 但是,我需要将它们更改为整数或浮点数,以便随后对它们进行一些计算。 有没有一种有效的方法来做到这一点(最好是没有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)
对不起你'后df.index.set_levels(projection.astype(INT),水平='ProjectionPeriod ',inplace = True)'? – EdChum
@EdChum:谢谢你的回答 - 'astype(int)'解决了问题 – Andreas