Python 如何从满足条件的数据帧中提取列和行索引
我想存储满足特定条件的所有数据框条目中的所有“坐标”(列位置和行位置)。在我的例子中,如果值大于0.8 这是我的密码:Python 如何从满足条件的数据帧中提取列和行索引,python,pandas,dataframe,Python,Pandas,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,
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)
用于位置,如果不是默认索引/列值,则按索引选择:
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]
你可以试试拉拉链
np.where将返回满足条件的索引,其中第一个数组中的行索引和以秒为单位的列索引都满足条件
arr = np.where(df_bool)
arr
(array([1, 2, 4], dtype=int64), array([1, 2, 0], dtype=int64))
list(zip(arr[0], arr[1]))
[(1, 1), (2, 2), (4, 0)]
rowArray = arr[0]
colArray = arr[1]
将
np.where
与np.column\u堆栈一起使用
:
randValues = np.random.rand(5,5)
df = pd.DataFrame(randValues)
df_bool = df > 0.8
ind = np.column_stack(np.where(df_bool)))
print(ind)
colArray = [i[1] for i in ind] # [2,3]
rowArray = [i[0] for i in ind] # [0,1]
输出:
array([0,2],
[1,3])
array([0,2],
[1,3])