I'm trying to replace NaN values in one column when the adjacent column starts with a string.

starts_with ={'65S':'test1','95S':test2,'20S':"test3"}

Here is the DF

15  65String    NaN
16  95String    NaN
17  20String    NaN

I would like it to look like

15  65String    test1
16  95String    test2
17  20String    test3

2 Answers

2
Wen-Ben On

Using findall find the key in dict , the just map back the dict's value

df.c3=df.c2.str.findall('|'.join(starts_with.keys())).str[0].map(starts_with)
df
Out[110]: 
   c1        c2     c3
0  15  65String  test1
1  16  95String  test2
2  17  20String  test3
1
jezrael On

Use Series.str.extract with ^ for match start of string with Series.map by dictionary:

starts_with ={'65S':'test1','95S':'test2','20S':"test3"}

pat = '|'.join(r"^{}".format(x) for x in starts_with)
df['C'] = df['B'].str.extract('(' + pat + ')', expand=False).map(starts_with)
print (df)
    A         B      C
0  15  65String  test1
1  16  95String  test2
2  17  20String  test3