Ehsan
Ehsan

Reputation: 83

Importing data as an array for plotting in Python

I am new to this question. I hop to get benefit of your advice. Sorry if it is amateurish.

I have the following code which finally shows a plot. I just write one part of code.

...
cov = np.dot(A, A.T)
samps2 = np.random.multivariate_normal([0]*ndim, cov, size=nsamp)
print(samps2)
names = ["x%s"%i for i in range(ndim)]
labels =  ["x_%s"%i for i in range(ndim)]
samples2 = MCSamples(samples=samps2,names = names, labels = labels, label='Second set')
g = plots.getSubplotPlotter()
g.triangle_plot([samples2], filled=True)

It has no problem. The plot is drawn using the data coming from samps2. To see what the samps2 is, we do print(samps2) and see:

[[-0.11213986 -0.0582685 ]
 [ 0.20346731  0.25309022]
 [ 0.22737737  0.2250694 ]
 [-0.09544588 -0.12754274]
 [-1.05491483 -1.15432073]
 [-0.31340717 -0.36144749]
 [-0.99158936 -1.12785124]
 [-0.5218308  -0.59193326]
 [ 0.76552123  0.82138362]
 [ 0.65083618  0.70784292]]

My question is, If I want to read these data from a txt file. what should I do?

Thank you.

Upvotes: 0

Views: 252

Answers (1)

SpghttCd
SpghttCd

Reputation: 10860

There are several ways. What comes to my mind is:

plain python:

data = []
with open(filename, 'r') as f:
    for line in f:
        data.append([float(num) for num in line.split()])

numpy:

import numpy as np
data = np.genfromtxt(filename, ...)

pandas:

import pandas as pd
df = pd.read_table(filename, sep='\s+', header=None)

Upvotes: 3

Related Questions