【发布时间】:2019-11-20 13:47:32
【问题描述】:
我正在调试一些意外创建 MultiIndex 而不是常规索引的 pandas 代码。由于多索引,Pandas 不允许选择列。在这种情况下,我可以摆脱 MultiIndex,但如果我确实需要 MultiIndex,你如何选择一列? 附加信息——我在使用 pandas 0.25.1 时遇到了这个错误,但这段代码是在几年前有人写的笔记本中,所以显然它曾经适用于旧版本?
import numpy as np
import pandas as pd
names = ['FirstColumn', 'SecondColumn']
data = np.array([[5,6],[7,8]])
df = pd.DataFrame(data, columns = [names]) #Bug: this "works" but isn't what you want.
#The brackets around "[names]" creates a multi-index but that was unintentional.
#But "df.head()" and "df.describe()" both look normal so you can't see anything is wrong.
df['FirstColumn'] #ERROR! works fine with a single index, but fails with multiindex
df.FirstColumn #ERROR! works fine with a single index, but fails with multiindex
df.loc[:,'FirstColumn'] #ERROR! works fine with a single index, but fails with multiindex
这两个陈述都给出了关于 only integer scalar arrays can be converted to a scalar index 的误导性错误
那么当存在多索引时如何选择列呢?我知道一些技巧,例如unstack 或更改索引等;但似乎应该有一个简单的方法?
更新:原来这在 pandas 0.22.0 中运行良好,但在 0.25.1 中失败。看起来引入了回归错误。我已经在pandas github上报告了。
【问题讨论】: