Not understanding why my Python else statement is causing an infinite loop?
m = 0
while m < len(dataframe):
if dataframe['firstname'].iloc[m] == 'Donald':
dataframe.loc[m, 'lastname'] = 'Trump'
elif dataframe['firstname'].iloc[m] == 'Joe':
dataframe.loc[m, 'lastname'] = 'Biden'
elif dataframe['firstname'].iloc[m] == 'Barrack':
dataframe.loc[m, 'lastname'] = 'Obama'
else:
dataframe.loc[m, 'lastname'] = 'last name does not matter'
m+=1
I have tested your code locally. I don't have infinite loop. Here is the code I have:
import pandas as pd
dataframe = pd.DataFrame({"firstname": ["Donald", "Joe", "Barrack", "Kamala"], "lastname": ["", "", "" ,""]})
m = 0
while m < len(dataframe):
if dataframe['firstname'].iloc[m] == 'Donald':
dataframe.loc[m, 'lastname'] = 'Trump'
elif dataframe['firstname'].iloc[m] == 'Joe':
dataframe.loc[m, 'lastname'] = 'Biden'
elif dataframe['firstname'].iloc[m] == 'Barrack':
dataframe.loc[m, 'lastname'] = 'Obama'
else:
dataframe.loc[m, 'lastname'] = 'last name does not matter'
m+=1
print(dataframe)
I would recommend using for loops so you can't get infinite loops though:
import pandas as pd
dataframe = pd.DataFrame({"firstname": ["Donald", "Joe", "Barrack", "Kamala"], "lastname": ["", "", "" ,""]})
for i in range(len(dataframe)):
if dataframe['firstname'].iloc[i] == 'Donald':
dataframe.loc[i, 'lastname'] = 'Trump'
elif dataframe['firstname'].iloc[i] == 'Joe':
dataframe.loc[i, 'lastname'] = 'Biden'
elif dataframe['firstname'].iloc[i] == 'Barrack':
dataframe.loc[i, 'lastname'] = 'Obama'
else:
dataframe.loc[i, 'lastname'] = 'last name does not matter'
print(dataframe)
Hope this helps!