我有一个numpy数组,如下所示:
np.array([
[1, 0, 0.5, 1, 0],
[0, 0, 0, 0, 0],
[1, 0, 0, 1, 0]
])
有人能提出获得一维索引数组的最快方法吗?其中,对于每个索引,数组中至少有一行的索引处有一个值>0?因此,对于上面的数组,所需的输出是(数据类型是什么并不重要,即列表与数组与系列等):
[0, 2, 3]
如果以上内容不清楚,请告诉我。目前,在我的真实用例中(如下),我从一个数据帧开始,转换为序列,转向numpy数组,获取非零索引,在这些索引处获取列。然而,我怀疑对数据帧进行一次操作(转换为numpy数组之后)会比
iterrows()
方法:
df1 = pd.DataFrame([
[1, 0, 0.5, 1, 0],
[0, 0, 0, 0, 0],
[1, 0, 0, 1, 0]
],
columns = ['c1', 'c2, 'c3', 'c4', 'c5'],
index = ['r1', 'r2', 'r3'])
set1 = set()
#This is what I would like to replace by going np.some_np_function(df1.to_numpy())
for protein, row in df1.iterrows():
non_zero_indexes = list(row.to_numpy().nonzero()[0])
columns_with_positive = [p for i,p in enumerate(row.index) if i in non_zero_indexes]
set1.update(columns_with_positive)
谢谢
蒂姆