Home > OS >  Join an array to every row in the pandas dataframe
Join an array to every row in the pandas dataframe

Time:11-02

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?

CodePudding user response:

Just plain assignment:

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

CodePudding user response:

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

CodePudding user response:

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

CodePudding user response:

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
  • Related