1

df1 has shape 4 column with 5 rows, and df2 has shape 2 columns with 7 rows.

I need to assign 1 column consisting of 10 rows into df2 consisting of 7 rows. , starting at index 1. df1

  First Name      last Name         
1. John          Smith              
2. Mary          Brohowski           
3. Aristidis     Papageorgopoulos   
4. James         Watss               
5. Kid           Red               

df2

 First Name     Last Name   
0. Marty          Smith
1. Sandy          Kevin          
2. Parry          Brohowski      
3. May            Dave      
4. Manny          Garido         
5. Rudy           Red         
6. Wesley         Rednap         
7. Ben            Papageo        

how can i change rows 1:5 in First Name column in df2, starting with index 0 with df1 Name column, starting with column 1 so the out put will be :

df2

   First Name     Last Name   
0. Marty          Smith          
1. John           Kevin          
2. Mary           Brohowski      
3. Aristidis      Dave          
4. James          Garido     
5. Kid            Red
6. Wesley         Rednap         
7. Ben            Papageo  

ive tried:

df1 = df1.reset_index()

start_row = 1
i = 1
for i in range(start_row, len(df2)-1):

    while i < len(df2):
        df2[i] = df1[i]
    else:
        break

any help pls

2 Answers 2

2

Try merge to merge to dataframe.

new_df = df1.merge(left_on='Last Name', right_on='Last Name', how='left')
Sign up to request clarification or add additional context in comments.

Comments

2

You can do a combine_first() after selecting the First Name column as a dataframe:

df1[['First Name']].combine_first(df2)

  First Name  Last Name
0      Marty      Smith
1       John      Kevin
2       Mary  Brohowski
3  Aristidis       Dave
4      James     Garido
5        Kid        Red
6     Wesley     Rednap
7        Ben    Papageo

5 Comments

Great solution @anky_91, i have another situation to reproduce where df1['Person'] is the column instead of 'First Name' and i need to leave it as 'Person'. How would that work?
@Jienkles do you mean something like: df1[['First Name']].combine_first(df2).rename(columns={'First Name':'Person'}) ?
Or same way you can rename df2 first name to person and then do combine first. df1[['Person']].combine_first(df2.rename(columns={'First Name' :'Person' }))
@anky_91 how can i do the same thing but paste into a row from df2? grateful for your help
@Jienkles i am not clear with the question, but did you try swapping the df1 and df2 in the combine first? If yes, what is your expected result?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.