Brayden Nilson
Brayden Nilson

Reputation: 47

python numpy csv header in column not row

I have a script which produces a 15x1096 array of data using

np.savetxt("model_concentrations.csv", model_con, header="rows:','.join(sources), delimiter=",")

Each of the 15 rows corresponds to a source of emissions, while each column is 1 day over 3 years. If at all possible I would like to have a 'header' in column 1 which states the emssion source. When i use the option "header='source1,source2,...'" these labels get placed in the first row (like expected). ie.

2per         3rd_pvd    3rd_unpvd   4rai_rd     4rai_yd      5rmo        6hea
2.44E+00    2.12E+00    1.76E+00    1.33E+00    6.15E-01    3.26E-01    2.29E+00 ...
1.13E-01    4.21E-02    3.79E-02    2.05E-02    1.51E-02    2.29E-02    2.36E-01 ...

My question is, is there a way to inverse the header so the csv appears like this:

2per        7.77E+00    8.48E-01 ...
3rd_pvd     1.86E-01    3.62E-02 ...
3rd_unpvd   1.04E+00    2.65E-01 ...
4rai_rd     8.68E-02    2.88E-02 ...
4rai_yd     1.94E-01    8.58E-02 ...
5rmo        7.71E-01    1.17E-01 ...
6hea        1.07E+01    2.71E+00 ...
...

Upvotes: 1

Views: 389

Answers (1)

Alicia Garcia-Raboso
Alicia Garcia-Raboso

Reputation: 13913

Labels for rows and columns is one of main reasons for the existence of pandas.

import pandas as pd

# Assemble your source labels in a list
sources = ['2per', '3rd_pvd', '3rd_unpvd', '4rai_rd',
           '4rai_yd', '5rmo', '6hea', ...]

# Create a pandas DataFrame wrapping your numpy array
df = pd.DataFrame(model_con, index=sources)

# Saving it a .csv file writes the index too
df.to_csv('model_concentrations.csv', header=None)

Upvotes: 2

Related Questions