1

I want to read data from a .txt file and enter each column as a variable (say x_1, x_2, etc) Normally I use

x_1, x_2, x_3 = numpy.loadtxt('filename.txt', delimiter=',' , unpack = True)

Now the problem is each data file is going to have different number of columns. So I was looking for a way to create multiple variable names x_i

I tried using a dictionary with each key as an empty list in the following way:

features = dict(('x_%d' %i,[]) for i in range (1,n))   # n is specified by user

The problem is I want to convert these lists(x_1, x_2, etc into a matrix and carry out some matrix operations later. And I just cannot refer these keys as variables as in:

x_1.T                        # Transpose  OR
x_2 - Y                      # both x_2 and Y are matrices

And I don't want to use something like features['x_3'] every time. Any suggestions?

update: Okay found out a way: create a list of matrices and then refer to them as x[o], x[1], etc. Even though x is a list, x[2] is a matrix.

Any better/smarter solution?

2
  • You can utilize the locals() method. It'd be okay for smaller scripts and applications but it gets unruly fast IMO. Commented Aug 2, 2013 at 7:57
  • What's wrong with just using a 2 dimensional list? so you'd do x = numpy.loadtxt(...) and then x[0].T, x[1] - Y? Commented Aug 2, 2013 at 7:59

2 Answers 2

1

First load the file into a big array (matrix):

x = numpy.loadtxt('filename.txt', delimiter=',', unpack=True)

Now you can access the column vectors with

x1 = x[:,0]
x2 = x[:,1]

and use numpy functions on these variables

y = x1.dot(x2)
Sign up to request clarification or add additional context in comments.

Comments

0

Why don't you use a list called x instead?

x[1].T
x[2] - Y

It's only one extra keystroke compared to x_1, x_2, etc. If you don't want to use x[0], just put a None there.

Dynamically generating local or global varibles is a bad idea.

1 Comment

@ Lauritz: Yes exactly this is what I did as mentioned in my update, thanks anyways for the fast reply

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.