【问题标题】:Pandas won't allow selecting a column if there's a multi-index?如果有多索引,Pandas 将不允许选择列?
【发布时间】: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上报告了。

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    使用DataFrame.xs函数:

    print (df.xs('FirstColumn', axis=1, level=0))
      FirstColumn
    0           5
    1           7
    

    【讨论】:

    • 谢谢,这行得通。但是我是否会因为认为这非常不直观并且标准的“.loc”语法应该在这里工作而疯狂?
    • @user2543623 - 我认为因为它是非标准的MultiIndex,因为只有一个级别......
    猜你喜欢
    • 2018-10-07
    • 2014-01-01
    • 2017-05-19
    • 2021-10-24
    • 2020-09-05
    • 1970-01-01
    相关资源
    最近更新 更多