例如,这是数据框
1 2
high wide
high thin
short wide
short thin
我想选择包含值“wide”的所有行。假设我不知道哪一列包含这些值。
这只是一个简化的示例。我需要它来迭代组织成数组的唯一表值。
for uv in uniqueValues:
valueObjects = """select all the rows that contain uv"""
有没有办法在不为每个值确定一列的情况下执行此操作? 我的意思是,这可行
for uv in uniqueValues:
for col in table.columns:
colValues = table[col].unique()
if uv in colValues:
valueObjects = table[table[col] == uv]
break
但我希望有一个更优雅的解决方案。
最佳答案
使用boolean indexing
:
df = df[df.eq('wide').any(axis=1)]
#alternative
#df = df[(df == 'wide').any(axis=1)]
print (df)
1 2
0 high wide
2 short wide
详细信息:
首先比较所有值DataFrame.eq
或 ==
bool 值 DataFrame
:
print (df.eq('wide'))
1 2
0 False True
1 False False
2 False True
3 False False
然后按 DataFrame.any
每行至少测试一次 True
:
print(df.eq('wide').any(axis=1))
0 True
1 False
2 True
3 False
dtype: bool
关于python - 如果我不知道该值属于哪一列,如何选择具有特定值的行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55558600/