batrick_pateman
batrick_pateman

Reputation: 29

How to add a column from df1 to df2 if it not present in df2, else do nothing

I have 2 data frame from a basic web scrape using Pandas (below). The second table has less columns than the first, and I need to concat the dataframes. I have been manually inserting columns for a while but seeing as they change frequently I would like to have a function that can assess the columns in df2, check whether they are all in df2, and if not, add the column, with the data from df2.

import pandas as pd 

link = 'https://en.wikipedia.org/wiki/Opinion_polling_for_the_next_French_presidential_election'
df = pd.read_html(link,header=0)

df1 = df[1]
df1 = df1.drop([0])
df1 = df1.drop('Abs.',axis=1)

df2 = df[2]
df2 = df2.drop([0])
df2 = df2.drop(['Abs.'],axis=1)

Many thanks,

Upvotes: 0

Views: 282

Answers (1)

Shubham Periwal
Shubham Periwal

Reputation: 2248

@divingTobi's answer:

pd.concat([df1, df2]) does the trick.

Upvotes: 1

Related Questions