python - pandas 中的逆向查找 : get ordered lists of row- and column-names

标签 python pandas dataframe lookup indices

给定索引和列列表,可以使用 lookup() 轻松提取 pandas DataFrame 的元素。方法。有没有办法从给定的数据框中获取索引和列的有序列表(例如,在应用 bool 运算之后)?明确地说,我想要索引和列的名称,而不仅仅是它们的整数位置。

这是我想出的最接近的,尽管它有点扭曲:

In [137]: df = pandas.DataFrame({"a":range(3), "b":range(10,13), "c":range(20,23)}, index=list("ABC"))

In [138]: df
Out[138]: 
   a   b   c
A  0  10  20
B  1  11  21
C  2  12  22

In [139]: df % 3 == 0
Out[139]: 
       a      b      c
A   True  False  False
B  False  False   True
C  False   True  False

In [140]: numpy.where(df % 3 == 0)
Out[140]: (array([0, 1, 2]), array([0, 2, 1]))

In [141]: iindices, icolumns = numpy.where(df % 3 == 0)

In [142]: indices = df.index[iindices]

In [143]: columns = df.columns[icolumns]

我正在寻找的结果:

In [144]: indices, columns
Out[144]: 
(Index([u'A', u'B', u'C'], dtype='object'),
 Index([u'a', u'c', u'b'], dtype='object'))

更容易用肉眼观察的替代形式:

In [145]: zip(indices, columns)
Out[145]: [('A', 'a'), ('B', 'c'), ('C', 'b')]

(h/t Python - find integer index of rows with NaN in pandas )

最佳答案

怎么样:

>>> s = df.stack()
>>> s[s % 3 == 0].index.tolist()
[('A', 'a'), ('B', 'c'), ('C', 'b')]

一步一步,首先我们堆叠:

>>> s = df.stack()
>>> s
A  a     0
   b    10
   c    20
B  a     1
   b    11
   c    21
C  a     2
   b    12
   c    22
dtype: int64

选择:

>>> s % 3 == 0
A  a     True
   b    False
   c    False
B  a    False
   b    False
   c     True
C  a    False
   b     True
   c    False
dtype: bool

使用它来过滤系列:

>>> s[s % 3 == 0]
A  a     0
B  c    21
C  b    12
dtype: int64

获取索引:

>>> s[s % 3 == 0].index
MultiIndex(levels=[[u'A', u'B', u'C'], [u'a', u'b', u'c']],
           labels=[[0, 1, 2], [0, 2, 1]])

以及我们正在寻找的值:

>>> s[s % 3 == 0].index.tolist()
[('A', 'a'), ('B', 'c'), ('C', 'b')]

关于python - pandas 中的逆向查找 : get ordered lists of row- and column-names,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21271375/

相关文章:

python - 添加新列并计算比率

python - 从 URL 列表(每个 URL 包含一个唯一的表)中抓取表数据,以便将其全部附加到单个列表/数据帧中?

python - 将列表中的数据分配到 panda 数据框中的列中

python - 如何获取pandas中许多csv文件夹中的列的平均值?

python - 使用范围数据集返回 2 秒的累积和

python - AWS Python 层在本地运行

python - 让按钮执行脚本

python - 无法跨 Python 验证 RSASSA-PSS 签名 -> Go

python - 在 JSON 序列化中嵌套一组带有新 header 的列

python - Keras 分类器的准确度在训练期间稳步上升,然后下降到 0.25(局部最小值?)