python二维数组按照第一列排序,如何排序基于在Python第二列二维数组(numpy.ndarray)?...

I'm trying to convert all my codes to Python. I want to sort an array which has two columns so that the sorting must be based on the 2th column in the ascending order. Then I need to sum the first column data (from first line to, for example, 100th line). I used "Data.sort(axis=1)", but it doesn't work. Does anyone have any idea to solve this problem?

解决方案

Use .argsort() it returns an numpy.array of indices that sort the given numpy.array. You call it as a function or as a method on your array. For example, suppose you have

import numpy as np

arr = np.array([[-0.30565392, -0.96605562],

[ 0.85331367, -2.62963495],

[ 0.87839643, -0.28283675],

[ 0.72676698, 0.93213482],

[-0.52007354, 0.27752806],

[-0.08701666, 0.22764316],

[-1.78897817, 0.50737573],

[ 0.62260038, -1.96012161],

[-1.98231706, 0.36523876],

[-1.07587382, -2.3022289 ]])

You can now call .argsort() on the column you want to sort, and it will give you an array of row indices that sort that particular column which you can pass as an index to your original array.

>>> arr[arr[:, 1].argsort()]

array([[ 0.85331367, -2.62963495],

[-1.07587382, -2.3022289 ],

[ 0.62260038, -1.96012161],

[-0.30565392, -0.96605562],

[ 0.87839643, -0.28283675],

[-0.08701666, 0.22764316],

[-0.52007354, 0.27752806],

[-1.98231706, 0.36523876],

[-1.78897817, 0.50737573],

[ 0.72676698, 0.93213482]])

You can equivalently use numpy.argsort()

>>> arr[np.argsort(arr[:, 1])]

array([[ 0.85331367, -2.62963495],

[-1.07587382, -2.3022289 ],

[ 0.62260038, -1.96012161],

[-0.30565392, -0.96605562],

[ 0.87839643, -0.28283675],

[-0.08701666, 0.22764316],

[-0.52007354, 0.27752806],

[-1.98231706, 0.36523876],

[-1.78897817, 0.50737573],

[ 0.72676698, 0.93213482]])

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值