pmorim
pmorim

Reputation: 123

Setting variables from array

I was processing some data that I got while doing a project and coded this:

# Parse data from txt file
data = numpy.loadtxt(inFileName + '.txt', skiprows=3)
freq = data[:, 0]   # Mirror Frequency (Hz)
sdfreq = data[:, 1] # σ Frequency (Hz)
dist = data[:, 2]   # ∆X (m)
sddist = data[:, 3] # σ ∆X (m)

And I realized that the last 4 lines look repetitive and I was obviously not going to repeat doing that if I had 1000 more data parameters. I could obviously parse it into a dictionary but that would force me to call dataset['freq'][0] instead of simply freq[0]. I could also parse it into an object and call dataset.freq[0], which would be better. But, is there a way I can compact the code and still have the ability to use freq[0] (without using exec())?

Upvotes: 0

Views: 56

Answers (2)

Daniil Loban
Daniil Loban

Reputation: 4381

Just use unpack=True:

import numpy

data = numpy.loadtxt(inFileName + '.txt', skiprows=3 , unpack=True )
[freq, sdfreq, dist, sddist] = data

print(freq, sdfreq, dist, sddist)

Upvotes: 1

randomchars42
randomchars42

Reputation: 335

I'm not sure I understand every aspect of your problem but I think you are on the right track. Is this of some help to you?

import numpy as np

data = np.array([[1,2,3,4],[5,6,7,8]])

def assign(data):
    result = []

    for i in range(data.shape[1]):
        result.append(list(data[:,i]))

    return result

freq, sdfreq, dist, sddist = assign(data)

or shorter:

freq, sdfreq, dist, sddist = [list(data[:,i]) for i in range(data.shape[1])]

Explanation:

Instead of parsing the data into a dictionary you can assign the columns to individual variables in one step:

For each column ('i in range(data.shape1)') return the column 'data[:,i]' as you did manually.

Cave: you need to keep track of column indeces, if your dataset changes you need to insert a new variable at the exact position. Perhaps a structured table or pandas might be helpful in the long run (especially when it comes to 1000+ columns).

Upvotes: 1

Related Questions