mzm
mzm

Reputation: 383

Making a numpy array with mixed types and writing it as csv

I am trying to create a numpy array to hold different types like this:

na_csv_output = np.zeros((len(ldt_timestamps),1),dtype=('i4,i4,i4,a10,a10,i4'))

The problem with this is that all 6 values are stored as a single entry, whereas I would prefer it to be 6 columns so that they can be written properly as a CSV. Is there any way this can be done by using a numpy array? (or some other type like list)

P.S.

Even when I try to write the values that I get from the initial try to a file using

np.savetxt('eventResults.csv', na_csv_output, delimiter=",")

it says

TypeError: float argument required, not numpy.string_

so that's another problem.

Upvotes: 2

Views: 3496

Answers (3)

hpaulj
hpaulj

Reputation: 231325

with open('eventResults.csv','w') as f:
    for x in xx:
        np.savetxt(f,x,fmt='%f, %f, %f, %r, %r, %f')
        # np.savetxt(f,x,fmt='%r',delimiter=', ')

Upvotes: 0

mattexx
mattexx

Reputation: 6606

I would use pandas. It makes csv operations really easy.

import pandas as pd
# omit second argument to np.zeros to get 1-d data
na_csv_output = np.zeros((len(ldt_timestamps),),dtype=('i4,i4,i4,a10,a10,i4'))
df = pd.DataFrame(na_csv_output)
df.to_csv('eventResults.csv')

Upvotes: 0

gg349
gg349

Reputation: 22671

To access each column, use na_csv_output['f0'] or f1 f2, etc, where f stands for field.

To save it to a file, first make it a 1D array,

na_csv_output = np.zeros((len(ldt_timestamps)),dtype=('i4,i4,i4,a10,a10,i4'))

To save it, you can go for something like this for example

np.savetxt('eventResults.csv', na_csv_output, fmt='%f, %f, %f, string= %s %s, last number = %f', delimiter=",")

Upvotes: 2

Related Questions