NumPy 数据分析练习(节选)

52 阅读2分钟

# NumPy 数据分析练习

6. 如何在不影响原始数组的情况下替换满足条件的元素项?

难度等级: L2

问题: 将arr中的所有奇数替换为-1,而不改变arr。

给定:

arr = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])

期望的输出:

out
# >  array([ 0, -1,  2, -1,  4, -1,  6, -1,  8, -1])
arr
# >  array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])

答案:

arr = np.arange(10)
out = np.where(arr % 2 == 1, -1, arr)
print(arr)
out
# > [0 1 2 3 4 5 6 7 8 9]
array([ 0, -1,  2, -1,  4, -1,  6, -1,  8, -1])

15. 如何创建一个python函数来处理scalars并在numpy数组上工作?

难度等级: L2

问题: 转换适用于两个标量的函数maxx,以处理两个数组。

给定:

def maxx(x, y):
    """Get the maximum of two items"""
    if x >= y:
        return x
    else:
        return y

maxx(1, 5)
# > 5

期望的输出:

a = np.array([5, 7, 9, 8, 6, 4, 5])
b = np.array([6, 3, 4, 8, 9, 7, 1])
pair_max(a, b)
# > array([ 6.,  7.,  9.,  8.,  9.,  7.,  5.])

答案:

def maxx(x, y):
    """Get the maximum of two items"""
    if x >= y:
        return x
    else:
        return y

pair_max = np.vectorize(maxx, otypes=[float])

a = np.array([5, 7, 9, 8, 6, 4, 5])
b = np.array([6, 3, 4, 8, 9, 7, 1])

pair_max(a, b)
# > array([ 6.,  7.,  9.,  8.,  9.,  7.,  5.])

16. 如何交换二维numpy数组中的两列?

难度等级: L2

问题: 在数组arr中交换列1和2。

给定:

arr = np.arange(9).reshape(3,3)
arr

答案:

# Input
arr = np.arange(9).reshape(3,3)
arr

# Solution
arr[:, [1,0,2]]
# > array([[1, 0, 2],
# >        [4, 3, 5],
# >        [7, 6, 8]])

19. 如何反转二维数组的列?

难度等级: L2

问题: 反转二维数组arr的列。

给定:

# Input
arr = np.arange(9).reshape(3,3)

答案:

# Input
arr = np.arange(9).reshape(3,3)

# Solution
arr[:, ::-1]
# > array([[2, 1, 0],
# >        [5, 4, 3],
# >        [8, 7, 6]])

35. 如何从numpy数组中删除包含缺失值的行?

难度等级: L3:

问题: 选择没有任何nan值的iris_2d行。

给定:

# Input
url = 'https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data'
iris_2d = np.genfromtxt(url, delimiter=',', dtype='float', usecols=[0,1,2,3])

答案:

# Input
url = 'https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data'
iris_2d = np.genfromtxt(url, delimiter=',', dtype='float', usecols=[0,1,2,3])
iris_2d[np.random.randint(150, size=20), np.random.randint(4, size=20)] = np.nan

# Solution
# No direct numpy function for this.
# Method 1:
any_nan_in_row = np.array([~np.any(np.isnan(row)) for row in iris_2d])
iris_2d[any_nan_in_row][:5]

# Method 2: (By Rong)
iris_2d[np.sum(np.isnan(iris_2d), axis = 1) == 0][:5]
# > array([[ 4.9,  3. ,  1.4,  0.2],
# >        [ 4.7,  3.2,  1.3,  0.2],
# >        [ 4.6,  3.1,  1.5,  0.2],
# >        [ 5. ,  3.6,  1.4,  0.2],
# >        [ 5.4,  3.9,  1.7,  0.4]])