如何通过索引值和任意列中的值搜索pandas数据框

2023-12-20

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

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

Thanks!


您可以使用all() any() iloc[]运营商。检查官方文档 http://pandas.pydata.org/pandas-docs/dev/10min.html, or 这个线程 https://stackoverflow.com/questions/26558576/conditional-probability-density-estimation-in-python/26559206#26559206更多细节

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)])
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何通过索引值和任意列中的值搜索pandas数据框 的相关文章

随机推荐