0

I am currently working with a dataframe, which I am creating on the fly, basically what I have so far is as follows:

  In [2]: df
  Out[2]:
     A  B  C  D
  0  1  
  1  2  
  2  3  

and I have an array of data arrays in numpy as follows:

array = [[1,2,3], [4,5,6], [7,8,9]]

I have tried to fill my dataframe with this data to get the following layout:

  In [2]: df
  Out[2]:
     A  B  C  D
  0  1  1  2  3
  1  2  4  5  6
  2  3  7  8  9

What I have been trying to do is the following:

new_df = df.append({k:v for k,v in zip(list_columns,array}, ignore_index=True)

But I don't get the results I need, I don't have that much experience with pandas, is there an efficient way to do it?

Thanks in advance!

1 Answer 1

2

Try this:

df[['B', 'C', 'D']] = array

Output:

>>> df
   A  B  C  D
0  1  1  2  3
1  2  4  5  6
2  3  7  8  9

That will work whether the columns were already in the dateframe or not.

Sign up to request clarification or add additional context in comments.

3 Comments

@isaac Did my solution work for you?
yes it works! Thanks a lot! but what about if I have the columns in a list names, there is other option than put them each one in the df columns names manually? @richardec
I think you can just do df[list_columns] = array in that case.

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.