python 文件读写和数据清洗

2022-08-19 18:47:38
目录
一、文件操作1.1 csv文件读写1.2 excel文件读写二、数据清洗2.1 删除空值2.2 删除不需要的列2.3 删除不需要的行2.4 重置索引2.5 统计缺失2.6 排序

一、文件操作

    pandas内置了10多种数据源读取函数,常见的就是CSV和EXCEL使用read_csv方法读取,结果为dataframe格式在读取csv文件时,文件名称尽量是英文读取csv时,注意编码,常用编码为utf-8、gbk>使用to_csv方法快速保存

    1.1>
    #读取文件,以下两种方式:
    #使用pandas读入需要处理的表格及sheet页
    import pandas as pd
    df = pd.read_csv("test.csv",sheet_name='sheet1') #默认是utf-8编码
    #或者使用with关键字
    with open("test.csv",encoding="utf-8")as df: 
        #按行遍历
        for row in df:
            #修正
            row = row.replace('阴性','0').replace('00.','0.')
            ...
            print(row)
    
    #将处理后的结果写入新表
    #建议用utf-8编码或者中文gbk编码,默认是utf-8编码,index=False表示不写出行索引
    df.to_csv('df_new.csv',encoding='utf-8',index=False) 

    1.2>
    #读入需要处理的表格及sheet页
    df = pd.read_excel('测试.xlsx',sheet_name='test')  
    df = pd.read_excel(r'测试.xlsx') #默认读入第一个sheet
    
    #将处理后的结果写入新表
    df1.to_excel('处理后的数据.xlsx',index=False)

    二、数据清洗

    2.1>
    # 删除空值行
    # 使用索引
    df.dropna(axis=0,how='all')#删除全部值为空的行
    df_1 = df[df['价格'].notna()] #删除某一列值为空的行
    df = df.dropna(axis=0,how='all',subset=['1','2','3','4','5'])# 这5列值均为空,删除整行
    df = df.dropna(axis=0,how='any',subset=['1','2','3','4','5'])#这5列值任何出现一个空,即删除整行

    2.2>
    # 使用del, 一次只能删除一列,不能一次删除多列 
    del df['sample_1']  #修改源文件,且一次只能删除一个
    del df[['sample_1', 'sample_2']]  #报错
    
    #使用drop,有两种方法:
    #使用列名
    df = df.drop(['sample_1', 'sample_2'], axis=1) # axis=1 表示删除列
    df.drop(['sample_1', 'sample_2'], axis=1, inplace=True) # inplace=True, 直接从内部删除
    #使用索引
    df.drop(df.columns[[0, 1, 2]], axis=1, inplace=True) # df.columns[ ] #直接使用索引查找列,删除前3列

    2.3>
    #使用drop,有两种方法:
    #使用行名
    df = df.drop(['行名1', '行名2']) # 默认axis=0 表示删除行
    df.drop(['行名1', '行名2'], inplace=True) # inplace=True, 直接从内部删除
    #使用索引
    df.drop(df.index[[1, 3, 5]]) # df.index[ ]直接使用索引查找行,删除1,3,5行
    df = df[df.index % 2 == 0]#删除偶数行

    2.4>
    #在删除了行列数据后,造成索引混乱,可通过 reset_index重新生成连续索引
    df.reset_index()#获得新的index,原来的index变成数据列,保留下来
    df.reset_index(drop=True)#不想保留原来的index,使用参数 drop=True,默认 False
    df.reset_index(drop=True,inplace=True)#修改源文件
    #使用某一列作为索引
    df.set_index('column_name').head()

    2.5>
    #每列的缺失数量
    df.isnull().sum()
    #每列缺失占比
    df3.isnull().sum()/df.shape[0]
    #每行的缺失数量
    df3.isnull().sum(axis=1)
    #每行缺失占比
    df3.isnull().sum(axis=1)/df.shape[1]

    2.6>
    #按每行缺失值进行降序排序
    df3.isnull().sum(axis=1).sort_values(ascending=False)
    #按每列缺失率进行降序排序
    (df.isnull().sum()/df.isnull().count()).sort_values(ascending=False)

    到此这篇关于python 文件读写和数据清洗的文章就介绍到这了,更多相关python数据处理内容请搜索易采站长站以前的文章或继续浏览下面的相关文章希望大家以后多多支持易采站长站!