我通常会写
df[ (df.Col1>0.0001) | (df.Col2>0.0001) | (df.Col3>0.0001) ].index
获取条件为True的标签。如果我有很多专栏,并说我有一个元组
cols = ('Col1', 'Col2', 'Col3')
cols
是df列的子集。
是否有更简洁的方式来编写上述内容?
答案 0 :(得分:1)
您可以组合pandas.DataFrame.any
并列出索引以创建用于索引的掩码。
请注意,cols
必须是列表,而不是元组。
import pandas as pd
import numpy as np
N = 10
M = 0.8
df = pd.DataFrame(data={'Col1':np.random.random(N), 'Col2':np.random.random(N),
'Col3':np.random.random(N), 'Col4':np.random.random(N)})
cols = ['Col1', 'Col2', 'Col3']
mask = (df[cols] > M).any(axis=1)
print(df[mask].index)
# Int64Index([0, 1, 4, 5, 6, 7], dtype='int64')
答案 1 :(得分:0)
您可以使用'any'或'all'来使用列表理解:
import pandas as pd
import numpy as np
In [148]: df = pd.DataFrame(np.random.randn(25).reshape(5,5), columns=list('abcde'))
In [149]: df
Out[149]:
a b c d e
0 -1.484887 2.204350 0.498393 0.003432 0.792417
1 -0.595458 0.850336 0.286450 0.201722 1.699081
2 -0.437681 -0.907156 0.514573 -1.162837 -0.334180
3 -0.160818 -0.384901 0.076484 0.599763 1.923360
4 0.351161 0.519289 1.727934 -1.232707 0.007984
您希望给定行中的所有列都大于-1的示例
In [153]: df.iloc[ [row for row in df.index if all(df.loc[row] > -1)], :]
Out[153]:
a b c d e
1 -0.595458 0.850336 0.286450 0.201722 1.699081
3 -0.160818 -0.384901 0.076484 0.599763 1.923360
您希望给定行中的任何列大于-1
的示例In [154]: df.iloc[ [row for row in df.index if any(df.loc[row] > -1)], :]
Out[154]:
a b c d e
0 -1.484887 2.204350 0.498393 0.003432 0.792417
1 -0.595458 0.850336 0.286450 0.201722 1.699081
2 -0.437681 -0.907156 0.514573 -1.162837 -0.334180
3 -0.160818 -0.384901 0.076484 0.599763 1.923360
4 0.351161 0.519289 1.727934 -1.232707 0.007984