Skip to content
Advertisement

Loading data from a file and converting into an array in Python

I am trying to load the data from a file. There are 3 rows and columns and I want to convert into an array A with shape (3,3). How do I go about doing it?

import numpy as np
np.loadtxt('A.csv')[:, 0]

The data looks like

Data

The array A should be

A=np.array([[0.751900795,0.720029442,0.519947357],
[0.757660601,0.682370477,0.693973342],
[0.799340382,0.641430593,0.73287523]])

Advertisement

Answer

Following my comment, convert the file to a panda dataframe first to get rid of the empty rows in your dataset. Then convert the resulting dataframe to numpy.

data.csv

0.751900795,0.720029442,0.519947357

0.757660601,0.682370477,0.693973342

0.799340382,0.641430593,0.73287523

code

import pandas as pd

df = pd.read_csv('data.csv', header=None)
s = df. to_numpy()
print(s)

output

[[0.75190079 0.72002944 0.51994736]
 [0.7576606  0.68237048 0.69397334]
 [0.79934038 0.64143059 0.73287523]]

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement