简体   繁体   中英

Zip pandas dataframes into a new dataframe

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM