在python Numpy中附加和格式化多维数组 [英] appending and formatting multi dimensional arrays in python Numpy

查看:43
本文介绍了在python Numpy中附加和格式化多维数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想编写一个将值附加到 order 多维数组的代码.如果最后一列是 0 顺序 indx [-1:,1](第一列中最后一个元素的功能),它将追加 10000 到第二列,以及第一列上的 1 (1,10000).如果第一列的最后一个元素是 1 ,则它将在第一列中添加 2 ,在第二列中添加 20000 (2,20000).我如何在不使用for循环或列表理解的情况下编写此类代码.

I want to write a code that appends a value to the order multidimensional array. If the last column is 0 order indx[-1:,1] (function for the last element in the first column) the it will append 10000 to the second column as well as 1 on the first column (1, 10000). If the first column last element is 1 than it will append 2 in the first column and 20000 in the second column (2, 20000). How could i write such code without the use of a for loop or list comprehensions.

import numpy as np

order = np.array([[     0,  38846],
                  [     1,  51599],
                  [     0,  51599],
                  [     1,  52598],
                  [     0, 290480],
                  [     1, 335368],
                  [     0, 335916]])

预期产量

#if the last element on column 1 is 1
[[     0,  38846]
 [     1,  51599]
 [     0,  51599]
 [     1,  52598]
 [     0, 290480]
 [     1, 335368]
 [     0, 335916]
 [     2,  20000]]
#if the last element on column 1 is 0
[[     0  38846]
 [     1  51599]
 [     0  51599]
 [     1  52598]
 [     0 290480]
 [     1 335368]
 [     0 335916]
 [     1  10000]]

推荐答案

def extend(order):
    if order[-1, 0] == 0:
        return np.concatenate([order, np.array([[1, 10000]])], axis=0)
    elif order [-1, 0] == 1:
        return np.concatenate([order, np.array([[2, 20000]])], axis=0)

这篇关于在python Numpy中附加和格式化多维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆