how to remove a sublist stored in a list in python

Viewed 64

I want to create a list using a numpy array. I want to export the differences of the values in the array and also the first value of this array:

my_array=np.array([1, 4, 10])

Firstly I find out the differences:

differs=np.diff(my_array)

it gives me:

array([3, 6])

But I want to have:

[1, 3, 6]

I tried the following:

sep=[my_array[0], np.diff(my_array)]

But it gives me:

[1, array([3, 6])]

I tried also to convert the array into a list but again I have a sublist and I do not know how to only copy the numbers of that sublist into my main list. To do that i tried:

sep=[my_array[0], [i for i in  np.diff(my_array)]]

And it gave me:

[1, [3, 6]]

In advance, I do appreciate any help.

4 Answers

I would do it by prepending 0 before feeding to numpy.diff, i.e.:

import numpy as np
my_array=np.array([1, 4, 10])
differs=np.diff(np.hstack(([0],my_array)))
print(differs)

output:

[1 3 6]

Beware that this based solely on your single input-desired output pair, so please test this soultion for other case you might also encounter and write if it does what you want and if not what is actual output and desired output.

try:

sep=[my_array[0], *np.diff(my_array)]

[1, 3, 6]

numpy.diff has a parameter for this:

my_array=np.array([1, 4, 10])
res = np.diff(my_array,prepend=0)

output:

[1 3 6]

You are on right track, you just need to add prepend argument to assign starting value:

np.diff(my_array, prepend=0)
array([1, 3, 6])
Related