Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add element in first an last position - Python numpy array

Tags:

python

numpy

I want to add in my ndarray an element in the first and last position. For this example, I want to add 0 in the first position, and 1441 in the last position. But how?

<type 'numpy.ndarray'>
Out[185]:
array([  10,   20,   30,   40,   50,   60,   70,   80,   90,  100,  110,
        120,  130,  140,  150,  160,  170,  180,  190,  200,  210,  220,
        230,  240,  250,  260,  270,  280,  290,  300,  310,  320,  330,
        340,  350,  360,  370,  380,  390,  400,  410,  420,  430,  440,
        450,  460,  470,  480,  490,  500,  510,  520,  530,  540,  550,
        560,  570,  580,  590,  600,  610,  620,  630,  640,  650,  660,
        670,  680,  690,  700,  710,  720,  730,  740,  750,  760,  770,
        780,  790,  800,  810,  820,  830,  840,  850,  860,  870,  880,
        890,  900,  910,  920,  930,  940,  950,  960,  970,  980,  990,
       1000, 1010, 1020, 1030, 1040, 1050, 1060, 1070, 1080, 1090, 1100,
       1110, 1120, 1130, 1140, 1150, 1160, 1170, 1180, 1190, 1200, 1210,
       1220, 1230, 1240, 1250, 1260, 1270, 1280, 1290, 1300, 1310, 1320,
       1330, 1340, 1350, 1360, 1370, 1380, 1390, 1400, 1410, 1420, 1430,
       1440], dtype=int64)
like image 602
mikesneider Avatar asked Nov 26 '25 00:11

mikesneider


2 Answers

Use numpy.concatenate:

import numpy as np
a = np.array([1,2,3])
np.concatenate(([0], a, [4]))
# array([0, 1, 2, 3, 4])

Or numpy.r_:

np.r_[0, a, 4]
# array([0, 1, 2, 3, 4])
like image 104
Psidom Avatar answered Nov 27 '25 14:11

Psidom


Assume that:

a = numpy.array([10, ... , 1440]);

Insert 0 at the first position:

np.insert(a, 0, 0);

Reference at numpy.insert.

Append 1441 at the last position:

numpy.append(a, 1441);

Reference at numpy.append.

like image 40
T.Liu Avatar answered Nov 27 '25 13:11

T.Liu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!