Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
149 views
in Technique[技术] by (71.8m points)

python - How to use the function numpy.append

I have a problem using the function numpy.append. I wrote the following function as part of a larger piece of code, however, my error is reproduced in the folowing:

data = [
         [
          '3.5', '3', '0', '0', '15', '6', 
          '441', 'some text', 'some more complicated data'
         ], 
         [
          '4.5', '5', '1', '10', '165', '0', 
          '1', 'some other text', 'some even more complicated data'
         ]
       ]

def GetNumpyArrey(self, index):
    r = np.array([])
    for line in data:
        np.append(r, float(line[index]))

    print r

index < 6. the result is:

>> []

what am I doing wrong?

Thanks a lot !

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Unlike the list append method, numpy's append does not append in-place. It returns a new array with the extra elements appended. So you'd need to do r = np.append(r, float(line[index])).

Building up numpy arrays in this way is inefficient, though. It's better to just build your list as a Python list and then make a numpy array at the end.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...