GlaceCelery
GlaceCelery

Reputation: 1033

How to append a numpy array to a pandas dataframe

I'm trying to append a 3x2 numpy array to an existing dataframe. Something like this:

import pandas as pd
import numpy as np
df = pd.Dataframe({"A": [0,0,0], "B": [1,1,1]})
arr = np.arange(6).reshape(3, 2)

df[["C", "D"]] = arr  # NOPE!

How do I get this to work?

Upvotes: 1

Views: 5749

Answers (2)

Francesco Zambolin
Francesco Zambolin

Reputation: 601

It didn't work because you need to pass a df:

arr = pd.DataFrame(np.arange(6).reshape(3, 2))

df[["C", "D"]] = arr #YEP

#Output
    A   B   C   D

0   0   1   0   1

1   0   1   2   3

2   0   1   4   5

Upvotes: 0

Erfan
Erfan

Reputation: 42916

Use concat while converting your array to a dataframe:

df = pd.concat([df, pd.DataFrame(arr, columns=["C", "D"])], axis=1)

   A  B  C  D
0  0  1  0  1
1  0  1  2  3
2  0  1  4  5

Upvotes: 5

Related Questions