您现在的位置是:网站首页> 编程资料编程资料
python 文件读写和数据清洗_python_
2023-05-26
430人已围观
简介 python 文件读写和数据清洗_python_
一、文件操作
- pandas内置了10多种数据源读取函数,常见的就是CSV和EXCEL
- 使用read_csv方法读取,结果为dataframe格式
- 在读取csv文件时,文件名称尽量是英文
- 读取csv时,注意编码,常用编码为utf-8、gbk 、gbk2312和gb18030等
- 使用to_csv方法快速保存
1.1 csv文件读写
#读取文件,以下两种方式: #使用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 excel文件读写
#读入需要处理的表格及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数据处理内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!
您可能感兴趣的文章:
相关内容
- Python pywin32实现word与Excel的处理_python_
- python中list列表复制的几种方法(赋值、切片、copy(),deepcopy())_python_
- Python 实操显示数据图表并固定时间长度_python_
- python爬虫beautiful soup的使用方式_python_
- python3 requests中文乱码之压缩格式问题解析_python_
- python math模块使用方法介绍_python_
- Python计算标准差之numpy.std和torch.std的区别_python_
- Python 读取 Word 文档操作_python_
- Python实现将字典内容写入json文件_python_
- 实例详解Python中的numpy.abs和abs函数_python_
