我有一个看起来像这样的DataFrame:
0
[0, 0, 0, 0, 0] 0.0
[1, 0, 0, 0, 0] 1.0
...
[0, 1, 1, 1, 1] 0.0
[1, 1, 1, 1, 1] 1.0
我想将其子集包含给定数量的1的索引。
条件可能看起来像
lambda x: np.count_nonzero(x) == n
持续1秒。
我知道使用.loc可以按条件进行子集设置,并且有许多答案说明了在列上设置条件时如何进行设置。如果条件取决于索引本身,我什么都找不到解释方法。
我尝试了这个:
rounded.loc[np.count_nonzero(rounded.index) == n]
但是没有运气。我不确定是否有真正明显的东西在逃避我。
我只可以创建一个新列,将索引作为值和基于此的子集,但是我想知道是否有更优雅的解决方案。
在大熊猫中可以创建此索引,但这并不容易。
对我来说,先转换index
为list
s然后转换为array
:
mask = np.count_nonzero(np.array(rounded.index.values.tolist()), axis=1) == n
样品:
df = pd.DataFrame({0:[0,1.0,0,1], 'a':[[0,0],[1,0],[1,1],[0,1]]})
rounded = df.set_index('a').rename_axis(None)
print (rounded)
0
[0, 0] 0.0
[1, 0] 1.0
[1, 1] 0.0
[0, 1] 1.0
n = 1
mask = np.count_nonzero(np.array(rounded.index.values.tolist()), axis=1) == n
print (mask)
[False True False True]
print (rounded[mask])
0
[1, 0] 1.0
[0, 1] 1.0
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句