Skip to content
Advertisement

Problem: In dataset i have data of country,state and city. Where some state and city name is 0.so,I want to replace “0” value of state with city name

Cities = ['Acre','Ashdod','Ashqelon','Bat Yam','Beersheba','Bnei Brak','Caesarea','Dimona','Dor','Elat','Kefar Sava','Lod','Meron','Nahariyya','Nazareth','Netanya']

lst = []

for i in range(500):

    i = random.choice(Cities)
    print(i)
    lst.append(i)

Data.loc[(Data['country'] == 'Israel') & (Data['state'] == 0),'state'] = lst

I tried this method. In this code list some city of israel and generate 500 random value of it. And apply condition to insert data in israel state location where data is 0.

Advertisement

Answer

# mask data so you compute mask only once
mask = (Data['country'] == 'Israel') & (Data['state'] == 0)
# find the length
len_to_replace = len(Data[mask])
# replace
Data.loc[mask, 'state'] = [random.choice(Cities) for _ in range(len_to_replace)]
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement