如何在python中使用嵌套的for循环? [英] How to use nested for loops in python?

查看:66
本文介绍了如何在python中使用嵌套的for循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试根据Python中另一个数据框的值创建一个数组.我希望它像这样填充数组.

I'm trying to create an array based on values from another data frame in Python. I want it to fill the array as such.

If x > or = 3 in the dataframe then it inputs a 0 in the array. 
If x < 3 in the dataframe then it inputs a 1 in the array.  
If x = 0 in the dataframe then it inputs a 0 in the array.

下面是我到目前为止的代码,但结果显示为[0]

Below is the code I have so far but the result is coming out as just [0]

array = np.array([])

for x in df["disc"]:
    for y in array:    
        if x >= 3:
            y=0
        elif x < 3:
            y=1
        else:
            y=0

任何帮助将不胜感激.

推荐答案

使用numpy数组时,如果您完全可以避免在Python中使用显式循环,则效率会更高.(实际的循环在已编译的C代码中进行.)

When working with numpy arrays, it is more efficient if you can avoid using explicit loops in Python at all. (The actual looping takes place inside compiled C code.)

disc = df["disc"]

# make an array containing 0 where disc >= 3, elsewhere 1
array = np.where(disc >= 3, 0, 1)

# now set it equal to 0 in any places where disc == 0
array[disc == 0] = 0

也可以使用以下命令在单个语句中完成(除了 disc 的初始赋值):

It could also be done in a single statement (other than the initial assignment of disc) using:

array = np.where((disc >= 3) | (disc == 0), 0, 1)

此处, | 逐个元素地执行或"操作.测试布尔数组.(它比比较运算符具有更高的优先级,因此需要用括号括起来.)

Here the | does an element-by-element "or" test on the boolean arrays. (It has higher precedence than comparison operators, so the parentheses around the comparisons are needed.)

这篇关于如何在python中使用嵌套的for循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆