简体   繁体   中英

Python selecting matrix elements

I have some large txt files from which I want to extract my data into an array. They look like:

     0,   9137,   9138,   9138,   9139,   9139,   9140,   9141,   9141,   9142,   9143
    10,   9143,   9144,   9145,   9145,   9146,   9147,   9148,   9148,   9149,   9150
    20,   9151,   9151,   9152,   9153,   9154,   9154,   9155,   9156,   9157,   9158
    30,   9159,   9159,   9160,   9161,   9162,   9163,   9164,   9165,   9166,   9166
    40,   9167,   9168,   9169,   9170,   9171,   9172,   9173,   9174,   9175,   9176

and so on. My plan is to get row 1-column 2, row 1-column3, ..., row 1-column 11 into an array, then do the same for the rest of the rows and put it all into a single array. I'm trying this code

import numpy as np

a = np.loadtxt("datafile.txt", float)
for i > 0:
    if a[:,i]:
        #t = a[:6, :]  #get first six rows
print t

but I don't seem to be getting anywhere, just a lot of errors.

    for i > 0:
          ^
SyntaxError: invalid syntax

Any ideas?

You should probably read up on how for loops work. You need loop of some sort of collection.

Numpy will create the array for you are after if loaded properly. You are very close but based on your example I would change float to int since all of your data appear to be integers and provide a an explicit , delimiter, like this:

a = np.loadtxt("datafile.txt", int, delimiter=",")

Assuming you read in a successfully, you can use a.shape to get the dimensions of a and use that to loop over a range if you want to go that route. a.shape[0] returns the number of rows and a.shape[1] returns the number of columns:

for i in range(a.shape[1]):
    # this will loop over i from 0 to the column count in a
    print(a[0][i]) # print(a[0,i]) will also work but only on numpy array

As you can see, you can access elements i,j of the array with a[i][j] or a[i,j] . This would print each item in the first row of a but you probably don't want to do that. If your goal is to print the first 6 rows of a , you can do that without a loop, like this:

print(a[:6])

Thanks, bnjmn.

This works for me:

a = np.loadtxt('datafile.txt', int, delimiter=',') # import data
y = np.reshape(a, np.size(a))
pos = np.delete(y, np.arange(0, y.size, 11))

plt.plot(pos)
plt.xlabel(sample)
plt.ylabel(position)

and I get: 数字

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM