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

eagi6jfj  于 2022-12-16  发布在  其他
关注(0)|答案(1)|浏览(103)

我尝试选择数据,从文件中读取,由值1和0表示。我希望能够从值列表中选择行,同时选择其中每个选定行的值都为1的任何列。为了使它更复杂,我还希望从值列表中选择其中这些行的列中的所有值都为0的行。这可能吗?最后,如果除了Pandas数据框架之外的另一种方法能更好地工作,我愿意尝试。
需要说明的是,可以选择任何一列,我事先不知道是哪一列。
谢谢!

iqjalb3h

iqjalb3h1#

可以使用all()any()iloc[]运算符。有关详细信息,请查看official documentation或此线程

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

相关问题