3

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)
1
  • Instead of existing elements or insert one before current "first" and one after current "last"? Commented Dec 14, 2017 at 0:43

3 Answers 3

9

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])
Sign up to request clarification or add additional context in comments.

Comments

4

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.

Comments

1

Just to add to the existing answers, in case this isn't already clear: You can't expand an existing numpy array in place. So if you have

a = np.array([1,2,3])

There is no operation that you can do to a that would cause all existing references to a to now be [0, 1, 2, 3, 4], for example. If you need that sort of semantic, then you'll need to wrap a in a container object of some sort.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.