2d array to two columns in dataframe

Question:

I got the variable ‘v’ which is a 2d array:

in = v
out = 
array([[ 217.1,  252.5],
   [  73. ,   53. ],
   [  83. ,  827. ],
   ...,
   [ 129. , 1214. ],
   [ 118.6,  908.2],
   [  90. ,   99.5]])

I have a dataframe with multiple columns and now I want to add this array to it in 2 seperate columns. So:

x        y
271.1   252.5

and so on.

How can I do this?

I tried:

df["Q_pred"],df["r_pred"] = v

but this gives the error:

ValueError: too many values to unpack (expected 2)

I honestly don’t know how to do it.

Asked By: Steven Pauly

||

Answers:

That’s a correct idea, but you’ll need the transformed matrix:

import pandas as pd
import numpy as np

v = np.array([[ 217.1,  252.5],
    [  73. ,   53. ],
    [  83. ,  827. ],
    [ 129. , 1214. ],
    [ 118.6,  908.2],
    [  90. ,   99.5]])

df = pd.DataFrame()

df[["Q_pred", "r_pred"]] = v.T

    Q_pred  r_pred
0   217.1   252.5
1    73.0    53.0
2    83.0   827.0
3   129.0  1214.0
4   118.6   908.2
5    90.0    99.5

This works with an already populated dataframe, too:

df[["asdf", "qwetz"]] = v.T

    Q_pred  r_pred   asdf   qwetz
0   217.1   252.5  217.1   252.5
1    73.0    53.0   73.0    53.0
2    83.0   827.0   83.0   827.0
3   129.0  1214.0  129.0  1214.0
4   118.6   908.2  118.6   908.2
5    90.0    99.5   90.0    99.5

or shorter without transformation and in one line:

df = pd.DataFrame(v, columns=['Q_pred', 'r_pred'])

    Q_pred  r_pred
0   217.1   252.5
1    73.0    53.0
2    83.0   827.0
3   129.0  1214.0
4   118.6   908.2
5    90.0    99.5
Answered By: SpghttCd

It’s easy to add multiple columns at once to an existing DataFrame. Just assign using a list of your new columns, and convert your numpy array to a DataFrame:

df[['Q_pred', 'r_pred']] = pd.DataFrame(v)

   Q_pred  r_pred
0   217.1   252.5
1    73.0    53.0
2    83.0   827.0
3   129.0  1214.0
4   118.6   908.2
5    90.0    99.5
Answered By: user3483203

Another way is to index the column like this:

df["Q_pred"],df["r_pred"] = v[:,0], v[:,1]
Answered By: Pedro Borges