7

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.

1
  • Don't get me wrong, it's not about me or my answer but I'd like to understand: You have an attempt which doesn't work and three corrections how it would do the job: 1. make two vectors from one array and each have to be indexed (for the record: 12 characters more than your attempt) 2. add [ and ] 3. add .T. So now here comes my question:) Why is the most verbose one the accepted answer? Commented Nov 27, 2018 at 23:36

3 Answers 3

8

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
Sign up to request clarification or add additional context in comments.

1 Comment

Yes, one way would be to do it exactly the same (see edit). The other many ways are distributed over all the other answers (mainly @user3483203, @timgeb)
7

Another way is to index the column like this:

df["Q_pred"],df["r_pred"] = v[:,0], v[:,1]

Comments

5

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.