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. Really sorry if this is a dumb question - I have done my best to try multiple methods and look at related questions, but I still unsure why it doesn't work.
If I print x, it returns every month name perfectly.
monthName = []
for i in df["Month_Number"]:
x = calendar.month_abbr[i]
print(x)
The below stores the result (month names) it in a nice clean list (which is great).
monthName = []
for i in df["Month_Number"]:
x = calendar.month_abbr[i]
monthName.append(x)
I would then go on to solve my problem by doing this:
df["Month_Name"] = monthName
Why does the following ONLY return "NONE" when i integrate into the loop?
monthName = []
for i in df["Month_Number"]:
x = calendar.month_abbr[i]
df["Month_Name"] = monthName.append(x)
Why does the following only return the last value:
for i in df["Month_Number"]:
df["Month_Name"] = calendar.month_abbr[i]
I understand (to some degree) as to why append returns none, but was more interested in understanding why other approaches only return the LAST value.
解决方案
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"]]