Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/308.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 按条件查找dataframe中行和列的所有索引_Python_Pandas_Dataframe - Fatal编程技术网

Python 按条件查找dataframe中行和列的所有索引

Python 按条件查找dataframe中行和列的所有索引,python,pandas,dataframe,Python,Pandas,Dataframe,假设我有一个带有数值的数据框 如何在某个阈值上\下找到单元格的所有索引(“行”+“列”+“值”) 例如: df = pd.DataFrame([[1,2,3],[4,5,6]], columns=['a', 'b', 'c']) 我的门槛是2 我想得到: [[0,c,3],[1,a,4][1,b,5],[1,c,6]] 用于重塑、按多索引创建列、按筛选并最后转换为嵌套列表: c = df.stack().reset_index(name='val').query('val > 2').

假设我有一个带有数值的数据框

如何在某个阈值上\下找到单元格的所有索引(“行”+“列”+“值”)

例如:

df = pd.DataFrame([[1,2,3],[4,5,6]], columns=['a', 'b', 'c'])
我的门槛是2 我想得到:

[[0,c,3],[1,a,4][1,b,5],[1,c,6]]
用于重塑、按多索引创建列、按筛选并最后转换为嵌套列表:

c = df.stack().reset_index(name='val').query('val > 2').values.tolist()
print (c)
[[0, 'c', 3], [1, 'a', 4], [1, 'b', 5], [1, 'c', 6]]
另一个性能更好的numpy解决方案:

#create numpy array
arr = df.values
#create boolean mask
m =  arr > 2
#get positions ot True values
a = np.where(m)
#filter values to 1d array by mask
b = arr.ravel()[m.ravel()]

#final list by indexinf columns and index values, map for convert nested tuples
c = list(map(list, zip(df.index[a[0]], df.columns[a[1]], b)))
print (c)
[[0, 'c', 3], [1, 'a', 4], [1, 'b', 5], [1, 'c', 6]]
您可以使用:

df[df.gt(2)].stack().reset_index().values.tolist()
输出:

[[0, 'c', 3.0], [1, 'a', 4.0], [1, 'b', 5.0], [1, 'c', 6.0]]