PingPong
PingPong

Reputation: 975

Join an array to every row in the pandas dataframe

I have a data frame and an array as follows:

df = pd.DataFrame({'x': range(0,5), 'y' : range(1,6)})
s = np.array(['a', 'b', 'c'])

I would like to attach the array to every row of the data frame, such that I got a data frame as follows:

enter image description here

What would be the most efficient way to do this?

Upvotes: 1

Views: 1039

Answers (4)

Ch3steR
Ch3steR

Reputation: 20669

You can try using df.loc here.

df.loc[:, s] = s

print(df)

   x  y  a  b  c
0  0  1  a  b  c
1  1  2  a  b  c
2  2  3  a  b  c
3  3  4  a  b  c
4  4  5  a  b  c

Upvotes: 1

Quang Hoang
Quang Hoang

Reputation: 150745

Just plain assignment:

# replace the first `s` with your desired column names
df[s] = [s]*len(df)

Upvotes: 3

mozway
mozway

Reputation: 260745

You could use pandas.concat:

pd.concat([df, pd.DataFrame(s).T], axis=1).ffill()

output:

   x  y  0  1  2
0  0  1  a  b  c
1  1  2  a  b  c
2  2  3  a  b  c
3  3  4  a  b  c
4  4  5  a  b  c

Upvotes: 1

Pedro Maia
Pedro Maia

Reputation: 2732

Try this:

for i in s:
    df[i] = i

Output:

   x  y  a  b  c
0  0  1  a  b  c
1  1  2  a  b  c
2  2  3  a  b  c
3  3  4  a  b  c
4  4  5  a  b  c

Upvotes: 1

Related Questions