Python Forum
Add a column in a dataframe from another dataframe
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Add a column in a dataframe from another dataframe
#1
Hi there,

I'm a newbie in Python and I need your help.
I tried to search my answer in the forum but I think I don't have the good keywords... It's a shame because the issue seems to be simple (but I'm even not sure of this !). Here's the problem :
I work with 2 dataframes df1 and df2.

df1 has n rows and 3 columns (A has only "NaN") :


ColA |ColB| ColC
_____________________________
NaN | B4 | C1
NaN | B4 | C2
NaN | B1 | C3
...... | .... | ....
NaN | B39 | C(n-1)
NaN | B74 | Cn


df2 has n rows and 2 columns (A and B) :


ColA|ColB
____________________
A1 | B1
A2 | B2
A3 | B3
.... | ....
A(n-1) | B(n-1)
An | Bn


The goal here is to fill the A column from df1 thanks to df2 and to get a dataframe like this :

df1 wanted :
ColA|ColB| ColC
_____________________________
A4 | B4 | C1
A4 | B4 | C2
A1 | B1 | C3
.... | .... | ....
A74 | B74 | Cn

I tried a lot of things (double for loops, pandas methods, etc.) but nothing worked. I think I don't have enough experience.

Someone can direct me towards the good way to solve the issue ?

Thanks !

Bilsix.
Reply
#2
Hiya, Bilsix!

You want to join two tables together. Use the DataFrame.join() method to join them together. This method will create a new DataFrame so be sure to store it.
Reply
#3
Hi stullis,

This method does exactly what I want !
Thanks a lot !

I solved my issue temporarely with a double for loop, but I'll use the "join" method, which is much more clear.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
Photo Converting Pandas DataFrame to a table of hourly blocks Abedin 1 518 Apr-24-2025, 01:05 PM
Last Post: snippsat
  renaming a column without a name in a dataframe Carbonpony 2 984 Jan-23-2025, 08:20 AM
Last Post: Carbonpony
  dataframe merge gunther 2 618 Jan-22-2025, 05:23 PM
Last Post: Pedroski55
  Running search/replace across Polars dataframe columns efficiently hobbycoder 3 2,333 Oct-28-2024, 03:18 AM
Last Post: hobbycoder
  Most efficient way to roll through a pandas dataframe? sawtooth500 2 1,155 Aug-28-2024, 10:08 AM
Last Post: Alice12
  Confused by the different ways of extracting data in DataFrame leea2024 1 698 Aug-17-2024, 01:34 PM
Last Post: deanhystad
  docx file to pandas dataframe/excel iitip92 1 2,680 Jun-27-2024, 05:28 AM
Last Post: Pedroski55
  FutureWarning: The behavior of DataFrame concatenation with empty or all-NA entries sawtooth500 14 8,222 Apr-24-2024, 01:42 AM
Last Post: sawtooth500
  Elegant way to apply each element of an array to a dataframe? sawtooth500 7 2,750 Mar-29-2024, 05:51 PM
Last Post: deanhystad
  Dataframe copy warning sawtooth500 4 2,245 Mar-25-2024, 11:38 PM
Last Post: sawtooth500

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020