Python For Loops Returning Last Value | Explanation

后端 未结 1 676
悲哀的现实
悲哀的现实 2021-01-29 09:53

I have a simple problem which I\'ve solved but it would be great if someone could explain why for loops do this in python and if there is a more elegant way. Re

1条回答
  •  别那么骄傲
    2021-01-29 10:12

    First way, append() doesn't return anything, so its return value will be None.

    Second way, nothing is "being returned", you are overwriting the value within a loop, then only inspecting the value of the entire df["Month_Name"] column after the final iteration, which by definition, will be the last value.

    I think using loops is the wrong approach here, you should be using apply or map functions instead, but if you wanted a loop, I might suggest this

    df["Month_Name"] = [calendar.month_abbr[i] for i in df["Month_Number"]]
    

    0 讨论(0)
提交回复
热议问题