![](/img/trans.png)
[英]How to find the index of an array where the value is larger than some threshold in numpy?
[英]Retrieve value larger than a threshold value from numpy array optimally
我正在使用 python 3.x。 我有一个 numpy 形状数组 (29982,29982) 和一个形状列表 29982。示例数组看起来像
array([[1,5,7,2,9...],
[2,6,4,1,5...],
[7,9,1,12,4...],
...
...
[6,8,13,2,4...]])
示例列表看起来像
['John','David','Josua',......,'Martin']
我想得到一个组合这个数组和列表的熊猫数据框,这样数组值应该大于5。数据框应该看起来像
'John' 'David' 'Josua'
'John' 0 0 7
'David' 0 6 0
'Josua' 7 9 0
....
'Martin' 6 8 13
你能建议我该怎么做吗?
只需使用pd.DataFrame
从数组创建数据框,将您的列表作为index
和columns
传递。 然后使用df.where
仅保留大于 5 的值:
arr = [...]
lst = ['John','David','Josua',...,'Martin']
df = pd.DataFrame(arr, index=lst, columns=lst)
df = df.where(df > 5, 0)
您可以尝试numpy.ma.masked_where
在 numpy 数组上进行处理
arr = np.array([[1,5,7,2,],
[2,6,4,1,],
[7,9,1,12],
[6,8,13,2]])
lst = ['John','David','Josua', 'Martin']
df = pd.DataFrame(np.ma.masked_where(arr<=5, arr).filled(0), index=lst, columns=lst)
print(df)
John David Josua Martin
John 0 0 7 0
David 0 6 0 0
Josua 7 9 0 12
Martin 6 8 13 0
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.