Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Zip pandas dataframes into a new dataframe

Tags:

python

pandas

I have 2 dataframes:

df_A

   country_codes
0              4
1              8
2             12
3             16
4             24

and df_B

   continent_codes
0                4
1                3
2                5
3                6
4                5

Both dataframes have same length, but no common column. I want to concatenate the two but since not all values are common, I get lots of NaNs. How do I concatenate or zip them up into a combined dataframe?

-- EDIT desired output is this:

   country_codes   continent_codes
0              4      4
1              8      3
2             12      5
3             16      6
4             24      5
like image 712
user308827 Avatar asked Dec 19 '22 21:12

user308827


2 Answers

The following code will do as you want :

pd.concat([df1, df2], axis=1)

Source

Output:

   country_codes  continent_codes
0              4                4
1              8                3
2             12                5
3             16                6
4             24                5
like image 89
FunkySayu Avatar answered Dec 21 '22 10:12

FunkySayu


From the comments:

I feel like this is too simple, but may I suggest:

df_A['continent_codes'] = df_B['continent_codes']
print(df_A)

Output:

   country_codes  continent_codes
0              4                4
1              8                3
2             12                5
3             16                6
4             24                5
like image 33
Niels Wouda Avatar answered Dec 21 '22 11:12

Niels Wouda