Python for loops and comprehension for loops

前端 未结 3 584
无人及你
无人及你 2021-01-24 03:45

Can someone explain to me why would this two statements (the for loop and the comprehension ) return two different answers. I thought they were the same, just different ways of

3条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-24 04:11

    you are setting the whole column (vector) in each iteration step:

    Top152['HighRenew'] = 1
    

    Try this vectorized approach instead:

    Top152['HighRenew'] = (Top152['% Renewable'] >= Top152['% Renewable'].median()).astype(int)
    

    so your function may be implemented as follows:

    def answer_ten():
        return (Top15['% Renewable'] >= Top15['% Renewable'].median()).astype(int)
    

提交回复
热议问题