python - 如何从满足条件的数据框中提取列和行索引
问题描述
我想存储满足特定条件的所有 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)
解决方案
用于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]
推荐阅读
- matplotlib - 在 p 中安装 matplotlib 时执行错误
- amazon-web-services - 如何在 AWS Amplify 中自动确认用户?
- python - 第 N 个斐波那契数
- javascript - 使用 setTimeOut 时无法清除窗口
- python - kivy._event.EventDispatcher.__init__ 引发错误“TypeError:object.__init__() 只采用一个参数(要初始化的实例)”
- javascript - 想要将 HTML 附加到文档时,使用 insertAdjacentHTML 是否存在任何安全风险?
- command-line - 如何从 Raku 命令行获取多个文件名?
- java - Selenium:无法在 https://www.phptravels.net/admin 中输入用户名
- wordpress - 获取 Twig/Timber 中的域名以在 WordPress 中输出?
- typescript - 试图坚持未发现的对象类型实体