richard-to
12/25/2013 - 11:41 AM

Running list basic numpy functions usage so I don't forget.

Running list basic numpy functions usage so I don't forget.

# Create a numpy array from a list
data = np.array(listData)

# Get a vector of elements in 2nd column -> [1, 2, 3]
# Remeber that the arrays are 0 indexed so technically it would be the 3rd column
colVec = data[:,2]

# Get a vector of elements 1st row -> [1, 2, 3]
# Don't forget the comma!
rowVec = data[1,:]

# Combine column vectors into matrix 
# Make sure to put parens around cols list to pass in as a single tuple
mat = np.column_stack((col1, col2))

# Replace values in column based on condition/predicate
# Replace text values with numeric values
# In this case all values were either female or male.
# Not sure if this works in all cases though
gender[gender == 'female'] = 0
gender[gender == 'male'] = 1

# This does not work!
# Will throw this error: "ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()"
np.where(age >= 20 and age < 36, 1, age)
np[age >= 20 and age < 36] = 1

# Instead need to use `np.logical_and`. Probably are other solutions too
# Need to make sure comparing against floats/ints and not strings
np.where(np.logical_and(age >= 20, age < 36), 1, age)