【问题标题】:How to search pandas data frame by index value and value in any column如何按索引值和任何列中的值搜索熊猫数据框
【发布时间】:2014-11-12 20:55:23
【问题描述】:

我正在尝试选择数据,从文件中读取,由值 1 和 0 表示。我希望能够从值列表中选择行,同时选择每个选定行的值为 1 的任何列。为了使其更复杂,我还想从值列表中选择行,其中这些行的列中的所有值都为零。这可能吗?最终,如果除了 pandas 数据框之外的另一种方法会更好,我愿意尝试。

需要明确的是,可以选择任何列,我不知道提前哪些列。

谢谢!

【问题讨论】:

  • 您能否提供一些示例数据以及所需的输出?

标签: python pandas selection


【解决方案1】:

您可以使用 all() any() ix[] 运算符。查看official documentationthis thread了解更多详情

import pandas as pd
import random
import numpy as np


#created a dump data as you didn't provide one
df = pd.DataFrame({'col1':  [random.getrandbits(1) for i in range(10)], 'col2':  [random.getrandbits(1) for i in range(10)], 'col3': [1]*10})

#You can select the value directly by using ix[] operator
row_indexer,column_indexer=3,1
print df.ix[row_indexer,column_indexer]

#You can filter the data of a specific column this way
print df[df['col1']==1]
print df[df['col2']==1]

#df.iloc to select by postion .loc to  Selection by Label

#want to be able to select rows from a list of values and at the same time select for any column in which each of the selected rows has a value of one.
print df[(df.T == 1).any()]
# if you wanna filter a specific columns with a condition on rows
print df[(df['col1']==1)|(df['col2']==1)]
#To make it more complex I also want to select rows from a list of values where all values in a column for these rows is zero.
print df[(df.T == 0).all()]
# if you wanna filter a specific columns with a condition on rows
print df[(df['col1']==0) & (df['col2']==0)]

【讨论】:

  • 我认为我们现在正试图鼓励人们使用.loc.iloc 而不是.ix,因为.ix 的语义难以解释。跨度>
  • Good point @DSM .loc/.iloc 在 0.11 中引入,鼓励用于用户索引选择。
猜你喜欢
  • 2013-02-03
  • 1970-01-01
  • 2017-10-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-21
  • 2016-08-06
  • 1970-01-01
相关资源
最近更新 更多