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=',')
CodePudding user response:
I would use pandas 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)