amen
amen

Reputation: 45

How to add an array as a column in existing csv file in python?

I have an array of response variables which I have got using regression analysis by using further code.

SalePrice_baseline = reg2.predict(test)

The output looks like,

array([[ 103612.29783843],
       [  95608.74582384],
       [ 178230.07228516],
       ..., 
       [ 172559.98073767],
       [ 121881.65675305],
       [ 218179.82985471]])

I have an existing test csv file of all the input variables as test.csv. I want to add this array as a new column.

How do I do that?

Thank you.

Upvotes: 0

Views: 1723

Answers (1)

gboffi
gboffi

Reputation: 25093

If the CSV file has the same number of lines as your vector, then you can read a line as a string, then print it plus a comma plus the corresponding vector value

with open('a.csv') as inp:
    with open('b.csv', 'w') as out:
        for line, value in zip(inp, vector)
            line = line.rstrip()
            print(line, ',', value, sep='', file=out)

Upvotes: 1

Related Questions