简体   繁体   中英

create a new column from 3 existing columns (python pandas)

I want to create a new column called ('Zoning Status) from the selection of 3 columns, namely the column (RT, RW, Kelurahan). For example, you want to search for Kelurahan 'Batu Ampar', RT 12 RW 2, RT 15 RW 5, RT 7 RW 4. Then the value will be zonasi_1 in the column ('zoning status'). Then Kelurahan 'Batu Ampar', RT 1 RW 4, RT 9 RW 3, RT 6 RW 5 then the value becomes zonation_2. Apart from the 2 conditions above, the value becomes zonation_3. I've tried using for and if else but it's not what I expected. sorry if my english is very bad. thank you before

status_zonasi = []
for x,y,z in zip(df_51['RT'], df_51['RW'], df_51['Kelurahan']):
    if x in [12, 15, 7, 11, 11, 10, 9 ,14] and y == [2, 5, 4, 4, 2, 2, 2, 2] and z == ['Batu Ampar']:
        c = 'Zonasi 1'
    elif x in [1, 9 , 6, 5, 8, 15, 17, 1, 10, 13, 4, 6, 12] and y == [4, 3, 5, 5, 2, 2, 2, 6, 4, 4, 4, 4, 4] and z == ['Batu Ampar']:
        c = 'Zonasi 2'
    else:
        c = 'Zonasi 3'
    status_zonasi.append(c)

enter image description here

You can make slices and apply your conditions to assign values like this:

df_51['Zoning_status'] = 'Zonasi 3'
df_51.loc[(df_51['RT'].isin([12, 15, 7, 11, 11, 10, 9 ,14])) & (df_51['RW'].isin([2, 5, 4, 4, 2, 2, 2, 2])) & (df_51['Kelurahan'] == 'Batu Ampar'), 'Zoning_status'] = 'Zonasi 1'
df_51.loc[(df_51['RT'].isin([1, 9 , 6, 5, 8, 15, 17, 1, 10, 13, 4, 6, 12])) & (df_51['RW'].isin([4, 3, 5, 5, 2, 2, 2, 6, 4, 4, 4, 4, 4])) & (df_51['Kelurahan'] == 'Batu Ampar'), 'Zoning_status'] = 'Zonasi 2'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM