1

After running an algorithm, I have two numpy arrays I'd like to combine so that I may export them to excel or to a matrix in Stata (I'll worry about the Stata part later). Consider the following code

import numpy as np

states = np.array(['Andalucia', 'Aragon', 'Asturias', 'Baleares', 'Canarias', 'Cantabria', 'Castilla Y Leon', 'Castilla-La Mancha', 'Cataluna', 'Comunidad Valenciana', 'Extremadura', 'Galicia', 'Madrid', 'Murcia', 'Navarra', 'Rioja'])

rscweights = np.array([-0.05427657,  0.18166224,  0.11563416,  0.09854334, -0.16184826,  0.1802778, 0.01034178, -0.18936965,  0.30148834,  0.0443326,  -0.08044339, -0.1048593, 0.24097428,  0.026126,   0.13228355,  0.1761398 ])

weights = np.hstack((states, rscweights))


print(weights)

weights.tofile('foo.csv',sep=',')

Ideally, I'd want the first column to be Andalucia, and cell two of row 1 to be -0.05427657, and so on and so forth. As previous posts have suggested, I've tried concatenate and hstack, but either way when I look at the resutlting csv file, all the names and numbers are on one line, instead of having two separate columns for these, as I'd want. How might I solve this? Perhaps reshape would be a solution?

import numpy as np

states = np.array(['Andalucia', 'Aragon', 'Asturias', 'Baleares', 'Canarias', 'Cantabria', 'Castilla Y Leon', 'Castilla-La Mancha', 'Cataluna', 'Comunidad Valenciana', 'Extremadura', 'Galicia', 'Madrid', 'Murcia', 'Navarra', 'Rioja'])

rscweights = np.array([-0.05427657,  0.18166224,  0.11563416,  0.09854334, -0.16184826,  0.1802778, 0.01034178, -0.18936965,  0.30148834,  0.0443326,  -0.08044339, -0.1048593, 0.24097428,  0.026126,   0.13228355,  0.1761398 ])

weights = np.concatenate((states, rscweights), axis=0)

print(weights)

weights.tofile('foo.csv',sep=',')
  • 1
    Does this answer your question? [Concatenate two NumPy arrays vertically](https://stackoverflow.com/questions/21887754/concatenate-two-numpy-arrays-vertically) – mkrieger1 Sep 25 '22 at 19:00
  • Beautifully. Thanks so much! @mkrieger1 – Jared Greathouse Sep 25 '22 at 19:12
  • Even if you make a 2d array with concatenate, `tofile` is going to write it as a flat line of numbers. There is `np.savetxt` that can write 2d arrays as a properly formatted `csv` file. – hpaulj Sep 25 '22 at 20:14

1 Answers1

0

I would use here, this would avoid any weird side effect of the conversion to string as a simple numpy concatenation generates an array of a single type:

import pandas as pd

df = pd.DataFrame({'states': states, 'rscweights': rscweights})

df.to_csv('outfile.csv', index=False)
mozway
  • 194,879
  • 13
  • 39
  • 75