admin管理员组文章数量:1321074
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
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
Share
Improve this question
asked Jan 17 at 20:56
MrMeMrMe
435 bronze badges
3
|
1 Answer
Reset to default 2I 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!
本文标签: python else statement causes a continuous loopStack Overflow
版权声明:本文标题:python else statement causes a continuous loop - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742091718a2420306.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
dataframe = pd.DataFrame({"firstname": ["Donald", "Joe", "Barrack", "Kamala"], "lastname": ["", "", "" ,""]})
– Barmar Commented Jan 17 at 21:10m+=1
at the beginning of the loop instead of the end, you would get an infinite loop because it assigns to the next row. When it reaches the last row of the df it adds a new row, so it never ends. – Barmar Commented Jan 17 at 21:12