numpy操作

numpy总结

 

 

 

 

 

 

 实践代码:

import numpy as np

t1 = np.arange(20).reshape((4, 5)).astype("float")

# 将第2行,第3,4列 复制为nan

t1[1, 3:5] = np.nan
print(t1)


def fill_ndarray(t1):
    '''
    将np数据每列为nan 的数据换成每列的平均值
    :param t1: 
    :return: 
    '''
    for i in range(t1.shape[1]):  # 遍历每一列
        temp_col = t1[:, i]  # 获取当前列
        nan_num = np.count_nonzero(temp_col != temp_col)
        if nan_num != 0:  # 不为0,说明当前列中有nan
            temp_not_nan_col = temp_col[temp_col == temp_col]  # 当前列不为nan 的数组
            # 选中当前为nan的位置,把均值赋值给它
            temp_col[np.isnan(temp_col)] = temp_not_nan_col.mean().astype("int")

    # return t1.astype("int")
    return t1


t2 = fill_ndarray(t1)
print(t2)

###numpy 读取csv 文件
d_lst = np.loadtxt("t.csv", delimiter=",", dtype="str")
age_lst = d_lst[1:, 0].astype("int")
print(type(age_lst))  # <class 'numpy.ndarray'>
print(age_lst.max(), age_lst.min())

 

posted @ 2020-12-15 00:36  冰底熊  阅读(74)  评论(0)    收藏  举报