0

I write a simple code list below:

data = np.array([[1,1,1],[2,3,4]])
xdata = [i + 0.1 for i in data[0]]
print(xdata)
data[0] = xdata
print(data)

But the result I get in console i

[1.1, 1.1, 1.1]
[[1 1 1]
 [2 3 4]]

While I expect it to be

[1.1, 1.1, 1.1]
[[1.1 1.1 1.1]
 [2 3 4]]

Why I can't change the value in NumPy array this way?

5
  • 1
    You need np.insert, Commented Oct 8, 2021 at 11:51
  • 2
    data as created can only hold int values. Commented Oct 8, 2021 at 11:59
  • 1
    stackoverflow.com/questions/44500787/… Commented Oct 8, 2021 at 12:00
  • 1
    I think your problem is similar to this question stackoverflow.com/questions/44500787/… Commented Oct 8, 2021 at 12:01
  • 1
    xdata = [i + 0.1 for i in data[0]] is better written a xdata = data[0]+0.1 Commented Oct 8, 2021 at 16:16

2 Answers 2

2

Create your array like this

data = np.array([[1,1,1],[2,3,4]], type=np.float64)

and it should work. Since you create the array with only integers, its data type becomes np.int64, which means that it can only hold integers.

Sign up to request clarification or add additional context in comments.

Comments

1

Your code works mostly as expected with one little problem:

This line

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

create a numpy-array of type int, and hence this line

data[0] = xdata

needs to truncate everything behind the decimal point. If you create a float array like this:

data = np.array([[1,1,1],[2,3,4]], dtype=float)

everything will work, as expected. However, if you just want to add to the first row 0.1 a nicer complete solution of your code is:

data = np.array([[1,1,1],[2,3,4]], dtype=float)
data[0] += 0.1

no list comprehension needed.

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.