Skip to content
Advertisement

combine pd.loc and pd.iloc to assign value

My input:

    import pandas as pd
dd = pd.DataFrame({'frame':[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15],
                   'sum_result_ICV':[0,1,1,1,2,2,2,2,1,1,1,1,1,1,1,0], 
                   'sum_result_ATO':[0,1,1,1,0,0,0,0,1,1,1,1,1,1,1,0]})
dd['result_ICV'] = 0
dd['result_ATO'] = 0
cv_detail = pd.Series(['ICV','ATO'])

I try assign new value based on other column in this way it work:

dd.loc[dd.iloc[:,1]==0,['result_'+cv_detail[0]] ] = 'Other' OR dd.loc[dd.sum_result_ICV == 0, "result_ICV"] = 'Other'
But this code doesn’t, code make more columns, with assign new value into column:

dd.loc[dd.iloc[:,1]==0, dd.iloc[:,3]] = 'Other'

What difference?

Advertisement

Answer

Use double iloc first for select second column by dd.iloc[:,1], conmvert to numpy array for possible assign in another iloc for fourth column (3):

dd.iloc[dd.iloc[:,1].to_numpy() == 0, 3] = 'Other'

print (dd)
    frame  sum_result_ICV  sum_result_ATO result_ICV  result_ATO
0       0               0               0      Other           0
1       1               1               1          0           0
2       2               1               1          0           0
3       3               1               1          0           0
4       4               2               0          0           0
5       5               2               0          0           0
6       6               2               0          0           0
7       7               2               0          0           0
8       8               1               1          0           0
9       9               1               1          0           0
10     10               1               1          0           0
11     11               1               1          0           0
12     12               1               1          0           0
13     13               1               1          0           0
14     14               1               1          0           0
15     15               0               0      Other           0
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement