Fill new pandas df based off values in another df

Viewed 48

I am new here, so please don't be to hard on me! :)

See picture below!

Print screen: df['Datan]

I am trying to create a new dataframe (df['New_df']) based on the values in df['Datan'] so that df['New_df'] is equal to df['Datan'] on the rows where the string #SRU appears. If the string is not in df['Datan'], I want df['New_df'] to "keep" the value of the row above (where the #SRU string was included).

See below df of what I am trying to do.

                                          Datan          New_df
                                 #SRU 1512 7251  #SRU 1512 7251
   #KONTO 1513 "Kundfordringar - delad faktura"  #SRU 1512 7251
                                 #SRU 1513 7251  #SRU 1513 7251
   #KONTO 1519 "Nedskrivning av kundfordringar"  #SRU 1513 7251
                                 #SRU 1519 7251  #SRU 1519 7251

I have been trying around with for loops combined with if statements with the apply method in particular but haven't reached a solution as of yet. Not able to find this specific problem in any other threads here.

2 Answers

Use, the combination of Series.str.contains, Series.mask & Series.ffill:

m = df['Datan'].str.contains(r'#SRU')
df['New_df'] = df['Datan'].mask(~m).ffill()

Result:

# print(df)
                                          Datan          New_df
0                                #SRU 1512 7251  #SRU 1512 7251
1  #KONTO 1513 "Kundfordringar - delad faktura"  #SRU 1512 7251
2                                #SRU 1513 7251  #SRU 1513 7251
3  #KONTO 1519 "Nedskrivning av kundfordringar"  #SRU 1513 7251
4                                #SRU 1519 7251  #SRU 1519 7251

Use str.contains to check string match and then use ffill to fill na

df['New_df'] = df.Datan.where(df.Datan.str.contains('#SRU')).ffill()
df
   Index                                           Datan            New_df
0     95                                 #SRU 1512 7251    #SRU 1512 7251
1     96   #KONTO 1513 "Kundfordringar - delad faktura"    #SRU 1512 7251
2     97                                 #SRU 1513 7251    #SRU 1513 7251
3     98   #KONTO 1519 "Nedskrivning av kundfordringar"    #SRU 1513 7251
4     99                                 #SRU 1519 7251    #SRU 1519 7251
Related