Jienkles
Jienkles

Reputation: 133

Assign a list to part of a column python

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

Upvotes: 1

Views: 53

Answers (2)

anky
anky

Reputation: 75080

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

Upvotes: 2

do thuan
do thuan

Reputation: 475

Try merge to merge to dataframe.

new_df = df1.merge(left_on='Last Name', right_on='Last Name', how='left')

Upvotes: 2

Related Questions