Riggun
Riggun

Reputation: 315

Numpy 2D array from TXT

Hello i need to create numpy 2D array from data stored in txt file. The main goal i want to achive is to use names instead of indexes [0][1] etc. I want to be able to call it like this: myarray['Date']['0'] for example.The sructure of TXT is: 2015-12-01,Jane,Adam,3.0,5.7,2.4 This is my code

from pylab import *
import matplotlib.pyplot as plt
from datetime import datetime
from matplotlib.dates import  DateFormatter, WeekdayLocator, HourLocator, \
     DayLocator, MONDAY
import numpy as np

mondays = WeekdayLocator(MONDAY)        # major ticks on the mondays
alldays    = DayLocator()              # minor ticks on the days
weekFormatter = DateFormatter('%b %d')  # e.g., Jan 12
dayFormatter = DateFormatter('%d')      # e.g., 12

#Here i create a class to store the array
class my_data:
    datalist=np.empty([],dtype={'names': ('Date', 'Name', 'Name2', 'Start', 'End','Avg'),
                    'formats': ('S10','S10', np.float, np.float, np.float,np.float)})

work=my_data()

#Here my read data function
def DataLd():
   list=[]
   data=[]
   NDate=0
   with open('DataBase/table.txt', "r") as f:
    for line in f:
        data=line.split(',')
        NDate = date2num(datetime.strptime(data[0], "%Y-%M-%d"))
        work.datalist=np.append(work.datalist,np.array([data[0],data[1],data[2],data[3],data[4],data[5]]),axis=0)
    print(work.datalist)

DataLd()

And this is the error

ValueError: zero-dimensional arrays cannot be concatenated

Upvotes: 0

Views: 443

Answers (1)

farhawa
farhawa

Reputation: 10417

I would suggest to load your txt as DataFrame instead of numpy.ndarray this way so you can get cells by name:

import pandas as pd

names = ['Date', 'Name', 'Name2', 'Start', 'End','Avg']

df = pd.DataFrame.from_csv("MyFile.txt",sep=",",index_col=False)
df.columns = names

# Than you can access to your data by name by index this way
df['Date'][0]

# To see types
df.dtypes

#To modify types
df.End.astype(float)

Upvotes: 0

Related Questions