Home > front end >  Add a Pandas dataframe beside an existing dataframe of the same size, i.e. on the next column
Add a Pandas dataframe beside an existing dataframe of the same size, i.e. on the next column

Time:10-30

I was playing around with data using pandas dataframe and bumped into this problem.

Is it possible to copy an existing dataframe and add the copy to next column of that particular dataframe?

I was able to do so if the dataframe have only one column of data.

df = pd.DataFrame(6*['a'])
copy = df.copy()
df.insert(len(df), len(df), copy)
print(df)

Which gave this

   0  6
0  p  p
1  p  p
2  p  p
3  p  p
4  p  p
5  p  p

But if I were to try inserting a dataframe with more than one column

df.insert(2, len(df), copy)
print(df)

which definitely gave an error since the insert function apparently supports adding one column at a time, I guess.

raise ValueError(f"cannot insert {item}, already exists")
ValueError: cannot insert 6, already exists

So, can anyone please give some suggestion on how to add a dataframe with more than one columns to another dataframe.

And should I be using numpy for this? I'm not quite familiar with numpy.

EDIT Would like to clarify things.

My original dataframe is this

   0  1
0  p  p
1  p  p
2  p  p
3  p  p
4  p  p
5  p  p

So, is there a way to copy the original dataframe and add it to the next column.

Expected output would be like this

  0  1  2  3
0  p  p  p  p
1  p  p  p  p
2  p  p  p  p
3  p  p  p  p
4  p  p  p  p
5  p  p  p  p

CodePudding user response:

insert only allows to insert one column at a time. If you want to insert 2 columns, you can use the concat method of pandas, passing the previous data frame and the new one, and setting the axis=1 so it is added as columns and not rows.

import pandas as pd
df = pd.DataFrame(6*['p'])
copy = df.copy()
df.insert(len(df.columns), len(df.columns), copy)
print(df)
copy = df.copy()
df = pd.concat([df, copy], axis=1)
print(df)
  • Related