python返回上一层循环_Python For循环返回最后一个值说明

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"]]

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值