Numpy IF-Statement over np.array - How?!


#1

Hey,

i want to count the years which are greater than 2000, i tried following code but it doesn’t work:

import numpy as np

class_year = np.array([1967, 1949, 2004, 1997, 1953, 1950, 1958, 1974, 1987, 2006, 2013, 1978, 1951, 1998, 1996, 1952, 2005, 2007, 2003, 1955, 1963, 1978, 2001, 2012, 2014, 1948, 1970, 2011, 1962, 1966, 1978, 1988, 2006, 1971, 1994, 1978, 1977, 1960, 2008, 1965, 1990, 2011, 1962, 1995, 2004, 1991, 1952, 2013, 1983, 1955, 1957, 1947, 1994, 1978, 1957, 2016, 1969, 1996, 1958, 1994, 1958, 2008, 1988, 1977, 1991, 1997, 2009, 1976, 1999, 1975, 1949, 1985, 2001, 1952, 1953, 1949, 2015, 2006, 1996, 2015, 2009, 1949, 2004, 2010, 2011, 2001, 1998, 1967, 1994, 1966, 1994, 1986, 1963, 1954, 1963, 1987, 1992, 2008, 1979, 1987])

start_counting = 0

for count in class_year:

if class_year<2000:
start_counting +=1

print (start_counting)

–> This error shows up:
Traceback (most recent call last): File “script.py”, line 8, in <module> if class_year <= 2000: ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

Can someone help me here ?

regards


#2

The problem lies here.

What you are saying here:
if the array named class_year is smaller than 2000

As you might know you cant compare a array with an integer. You would need to loop through this array and check every entry individually.

Something like this will work:

import numpy as np
class_year = np.array([1967, 1949, 2004, 1997, 1953, 1950, 1958, 1974, 1987, 2006, 2013, 1978, 1951, 1998, 1996, 1952, 2005, 2007, 2003, 1955, 1963, 1978, 2001, 2012, 2014, 1948, 1970, 2011, 1962, 1966, 1978, 1988, 2006, 1971, 1994, 1978, 1977, 1960, 2008, 1965, 1990, 2011, 1962, 1995, 2004, 1991, 1952, 2013, 1983, 1955, 1957, 1947, 1994, 1978, 1957, 2016, 1969, 1996, 1958, 1994, 1958, 2008, 1988, 1977, 1991, 1997, 2009, 1976, 1999, 1975, 1949, 1985, 2001, 1952, 1953, 1949, 2015, 2006, 1996, 2015, 2009, 1949, 2004, 2010, 2011, 2001, 1998, 1967, 1994, 1966, 1994, 1986, 1963, 1954, 1963, 1987, 1992, 2008, 1979, 1987])

start_counting = 0

for year in class_year:
    if year < 2000:  #using the year that is available trough the for each loop. 
        start_counting +=1

print (start_counting)

#3

Thank you biirra - that is it!

Regards!