如何按索引值和任意列的值搜索pandas数据框

9
我正在尝试从文件中读取由1和0表示的数据,并选择其中一些行。我想要能够从值列表中选择行,并且同时选择这些行中每个所选列的值都为1的列。更复杂的是,我还想从值列表中选择那些指定行中所有列的值都为0的行。这是否可能?如果除了pandas数据框架之外有其他更好的方法,我也愿意尝试。
明确一点,任何列都可以被选择,我事先不知道哪些列会被选择。
谢谢!

1
你能提供一些示例数据以及期望的输出吗? - joris
1个回答

11
你可以使用all()any()iloc[]运算符。请查看官方文档此帖子获取更多详细信息。
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})
print(df)

# You can select the value directly by using iloc[] operator
# df.iloc to select by postion .loc to  Selection by Label
row_indexer,column_indexer=3,1
print(df.iloc[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])

# 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)])

2
我认为现在我们正在鼓励人们使用.loc.iloc而不是.ix,因为.ix的语义难以解释。 - DSM
很好的观点 @DSM .loc/.iloc 在0.11中被引入,并鼓励用于用户索引选择。 - user4179775

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接