按内部值过滤列并获取索引

Filter column by value inside and get index

我想用值大于或等于 1 的列填充其他数据框。

df = pd.DataFrame({'A': '0 1 0 0 1 2'.split(),
               'B': '0.1 0.2 0 0.5 0 0.1'.split(),'C':'0.1 0.2 0 0.5 0 0.1'.split()})

   A    B    C
0  0  0.1  0.1
1  1  0.2  0.2
2  0    0    0
3  0  0.5  0.5
4  1    0    0
5  2  0.1  0.1

例如,我会这样得到 df2

df2 = pd.DataFrame({'A': '0 1 0 0 1 2'.split()})

如果我尝试 df2=df2[df2.values.astype(float) >= 1] 我会保留我的三列

您可以按列使用 ge what means get values greater or equal, then filter by any at least one True and last boolean indexing ix:

print (df.astype(float).ge(1, axis=1))
       A      B      C
0  False  False  False
1   True  False  False
2  False  False  False
3  False  False  False
4   True  False  False
5   True  False  False

print (df.astype(float).ge(1, axis=1).any())
A     True
B    False
C    False
dtype: bool

#sample data are strings, so first cast to float
df2 = df.ix[:, df.astype(float).ge(1, axis=1).any()]
print (df2)
   A
0  0
1  1
2  0
3  0
4  1
5  2

它也适用于:

df2 = df.ix[:, (df.astype(float) >= 1).any()]
print (df2)
   A
0  0
1  1
2  0
3  0
4  1
5  2

我创建了一个布尔掩码,其中列中至少有一些值 >= 1。然后我在数据和列上使用这个掩码来生成一个新的数据框。

我使用 numpy 进行屏蔽。

# convert to floats and define mask
v = df.values.astype(float)
mask = (v >= 1).any(0)

# assign new dataframe with masked data and masked columns
# just incase there where multiple columns that satisfied.
df2 = pd.DataFrame(v.T[mask].T, columns=df.columns[mask])
df2


时机

df 1000倍长

df = pd.concat([df.T for _ in range(1000)], ignore_index=True).T