perform condition check in pandas dataframe and copy the values of specific cols to another location in dataframe

Viewed 35

In the dataframe below, for those 'pred_id' which is NaN, I want to check the 'image_name' whether it is in 'pred_image' and if present, then copy the 'pred_id' and 'pred_image' values to the NaN cols respectively. If not present, then just leave it.

enter image description here

data = {'pred_id': [2051,2052,2053,2054,2055,np.nan,np.nan,np.nan],
        'pred_image':['app_images/prediction/162000_p_r.jpg', 'app_images/prediction/162100_p_r.jpg','app_images/prediction/162200_p_r.jpg','app_images/prediction/162300_p_r.jpg','app_images/prediction/162400_p_r.jpg',np.nan,np.nan,np.nan],
        'image_name':['162000.jpg','162100.jpg','162200.jpg','162300.jpg','162400.jpg','162100.jpg','162200.jpg','162700.jpg'],
        'pred_label':[1,2,4,1,2,1,1,2],
        'vol':[345,124,312,234,564,212,313,414]}

df = pd.DataFrame(data)

new_values= df[(df['pred_id'].isna())]
app = [df['pred_image']]
for i in new_values['image_name']:
    if i[:-4].isin(app):
        # then how to select that row and copy the values?

Expected output

enter image description here

1 Answers

With your data as shown, you can use groupby.transform('first'):

img_names = df.image_name.str[:-4]
df[['pred_id', 'pred_image']] = df.groupby(img_names)[['pred_id', 'pred_image']].transform('first')

Output:

   pred_id                            pred_image  image_name  pred_label  vol
0   2051.0  app_images/prediction/162000_p_r.jpg  162000.jpg           1  345
1   2052.0  app_images/prediction/162100_p_r.jpg  162100.jpg           2  124
2   2053.0  app_images/prediction/162200_p_r.jpg  162200.jpg           4  312
3   2054.0  app_images/prediction/162300_p_r.jpg  162300.jpg           1  234
4   2055.0  app_images/prediction/162400_p_r.jpg  162400.jpg           2  564
5   2052.0  app_images/prediction/162100_p_r.jpg  162100.jpg           1  212
6   2053.0  app_images/prediction/162200_p_r.jpg  162200.jpg           1  313
7      NaN                                   NaN  162700.jpg           2  414
Related