3

I am trying to add an integer to an array but I am getting an error. Here is my code:

import numpy as np
import h5py

for i in range(1, 621):
    with h5py.File("C:\\A" + str(i) + ".out") as f:
        data = np.array(f['rxs']['rx1']['Ey'])
        data.append(0)
    np.savetxt("C:\\A" + str(i) + ".csv", data, delimiter = ",")

For this I keep getting an error saying: "AttributeError: 'numpy.ndarray' object has no attribute 'append'"

I have also tried concatenate with an array consisting just 1 integer but it doesn't work. I used these lines for that:

data = np.array(f['rxs']['rx1']['Ey'])
b = np.array([[0]])
np.concatenate(data, b)

I get this error for this one: "TypeError: only integer scalar arrays can be converted to a scalar index"

The original aim of my code is to convert HDF files to CSV files which works if I don't try to change the array.

Could you please help?

7
  • 2
    try using np.append(a,0) Commented Feb 1, 2019 at 12:46
  • 1
    Be aware that np.append is inefficient as it always creates and returns a modified copy of the array. The original array isn't modified. Commented Feb 1, 2019 at 12:48
  • @MichaelButscher: Unless you store the result in the same array name Commented Feb 1, 2019 at 12:49
  • 2
    @Bazingaa But even then first a new array has to be allocated, data of previous array copied and finally the previous array deleted. For a Python list.append this happens only sometimes. Commented Feb 1, 2019 at 12:51
  • @MichaelButscher: So what are the situations when np.append should be used and when should it be avoided? Commented Feb 1, 2019 at 12:55

1 Answer 1

4

You are not dealing with a python list but a numpy array.

To solve the problem at hand you can use numpy.append

data = np.append(data, 0)

You can also not create a numpy array to begin with. What is the type of f['rxs']['rx1']['Ey']? (You can find out with print(type(f['rxs']['rx1']['Ey'])))

if it is a list, you can simply do

data = f['rxs']['rx1']['Ey']
data.append(0)
Sign up to request clarification or add additional context in comments.

2 Comments

Updated the answer with another suggestion. Accept the answer if it resolves your issue so other people do not look at the question
It says "<class 'h5py._hl.dataset.Dataset'>". But your answer solved my problem. Thanks!

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.