[英]Converting pandas.Multindex to numpy.ndarray with dtype float
将 pandas.Multiindex 转换为 numpy.ndarray 时,output 是一个 dtype dtype=object
的一维 ndarray,如下例所示:
df = pd.DataFrame({
'A': [10, 20, 30, 40, 50, 60],
'B': [0,1,2,3,4,5],
'C': ['K0', 'K1', 'K2', 'K3', 'K4', 'K5']
}).set_index(['A','B'])
df 将是:
一个 | 乙 | C |
---|---|---|
10 | 0 | K0 |
20 | 1 | K1 |
30 | 2 | K2 |
40 | 3 | K3 |
50 | 4 | K4 |
60 | 5 | K5 |
df.index.to_numpy()
的 output 是 dtype dtype=object
的一维 ndarray:
array([(10, 0), (20, 1), (30, 2), (40, 3), (50, 4), (60, 5)], dtype=object)
但我想要:
array([[10, 0],
[20, 1],
[30, 2],
[40, 3],
[50, 4],
[60, 5]])
关于如何将具有 object dtype 的 Numpy 2D 数组转换为浮点数的常规 2D 数组,我找到了以下解决方案:
np.vstack(df.index)
有没有更直接或更好的解决方案?
我很确定你会通过展平多索引并从结果中获取 numpy 数组来得到你想要的。 例如,使用以下语法
np.array(list(df.index))
将索引转换为列。
df.reset_index()[['A', 'B']].values
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.