首页 > 解决方案 > 如何从满足条件的数据框中提取列和行索引

问题描述

我想存储满足特定条件的所有 Dataframe 条目中的所有“坐标”(列位置和行位置)。就我而言,如果值大于 0.8。

这是我的代码:

import numpy as np
import pandas as pd


randValues = np.random.rand(5,5)

df = pd.DataFrame(randValues)
df_bool = df > 0.8


colArray = np.empty([])
rowArray = np.empty([])


for dfIdx, dfCol in enumerate(df_bool):
    row = dfCol.loc[dfCol['1'] == True]

    if ~row.isempty():
        colArray.append(dfIdx)
        rowArray.append(row)

标签: pythonpandasdataframe

解决方案


用于numpy.where位置,如果不是默认索引/列值,则通过索引选择:

np.random.seed(2019)
randValues = np.random.rand(5,5)

df = pd.DataFrame(randValues, columns=list('abcde'))
print (df)
          a         b         c         d         e
0  0.903482  0.393081  0.623970  0.637877  0.880499
1  0.299172  0.702198  0.903206  0.881382  0.405750
2  0.452447  0.267070  0.162865  0.889215  0.148476
3  0.984723  0.032361  0.515351  0.201129  0.886011
4  0.513620  0.578302  0.299283  0.837197  0.526650

r, c = np.where(df > 0.8)
print (r)
[0 0 1 1 2 3 3 4]
print (c)
[0 4 2 3 3 0 4 3]

colArray = df.columns.values[c]
print (colArray)
['a' 'e' 'c' 'd' 'd' 'a' 'e' 'd']

rowArray = df.index.values[c]
print (rowArray)
[0 4 2 3 3 0 4 3]

推荐阅读