python 读取.csv文件数据到数组(矩阵)的实例讲解
作者:yanyanyufei96 时间:2023-08-10 12:12:36
利用numpy库
(缺点:有缺失值就无法读取)
读:
import numpy
my_matrix = numpy.loadtxt(open("1.csv","rb"),delimiter=",",skiprows=0)
写:
numpy.savetxt('2.csv', my_matrix, delimiter = ',')
可能遇到的问题:
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position
原因是文件路径名中含有转义字符,将路径中的\换成\即可。
利用pandas库
读:(可以处理缺失值)
>>> import pandas as pd
>>> df = pd.read_csv('D:\Python\\l\B_train1.csv')
>>> df.values
>>> df.as_matrix(columns=None)
写:(将dataFrame直接写入)
>>> testB = test[test.intersection_id.isin(["B"])]
>>> pd.DataFrame.to_csv(testB,"D:\Python\\k\\t5B.csv")
#testB是个dataFrame
利用sklearn包中的Imputer处理缺失值
>>> m = df.as_matrix(columns=None)
>>> from sklearn.preprocessing import Imputer
>>> imp = Imputer(missing_values='NaN', strategy='mean', axis=0)
>>> imp.fit(m)
Imputer(axis=0, copy=True, missing_values='NaN', strategy='mean', verbose=0)
>>> imp.transform(m)
来源:https://blog.csdn.net/yanyanyufei96/article/details/70171887
标签:python,csv,数组
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Python如何设置指定窗口为前台活动窗口
2022-01-22 02:20:02
用于打印的页面设计
2009-07-06 12:47:00
vue+canvas实现拼图小游戏
2024-05-09 15:09:34
![](https://img.aspxhome.com/file/2023/3/126613_0s.jpg)
mysql中redo log和 binlog的区别
2024-01-14 12:43:52
![](https://img.aspxhome.com/file/2023/7/122867_0s.png)
python如何在word中存储本地图片
2022-09-13 02:17:53
![](https://img.aspxhome.com/file/2023/3/68343_0s.png)
python面向对象编程设计原则之单一职责原则详解
2022-02-13 20:51:25
![](https://img.aspxhome.com/file/2023/3/96943_0s.png)
使用ajax开发的五大误区
2008-09-03 12:46:00
django之导入并执行自定义的函数模块图解
2023-07-27 02:45:19
![](https://img.aspxhome.com/file/2023/0/86240_0s.jpg)
uniapp H5 https跨域请求实现
2024-04-10 16:20:27
![](https://img.aspxhome.com/file/2023/0/136700_0s.png)
Go语言利用ssh连接服务器的方法步骤
2024-04-25 14:59:55
![](https://img.aspxhome.com/file/2023/6/134276_0s.png)
python教程网络爬虫及数据可视化原理解析
2021-07-13 11:36:11
![](https://img.aspxhome.com/file/2023/7/124287_0s.png)
Python调用scp向服务器上传文件示例
2023-12-09 18:56:34
用户 jb51net 登录失败。原因: 该帐户的密码必须更改
2024-01-13 05:58:46
python中matplotlib的颜色及线条控制的示例
2023-11-04 08:11:50
![](https://img.aspxhome.com/file/2023/5/111985_0s.png)
解决Keras中Embedding层masking与Concatenate层不可调和的问题
2022-06-02 17:02:16
python实现键盘输入的实操方法
2022-07-25 19:18:25
![](https://img.aspxhome.com/file/2023/5/121485_0s.jpg)
在Python的setuptools框架下生成egg的教程
2021-12-06 13:46:33
VUEJS实战之修复错误并且美化时间(2)
2023-07-02 17:01:24
![](https://img.aspxhome.com/file/2023/3/139893_0s.jpg)
python去除文件中空格、Tab及回车的方法
2021-12-04 22:25:44
OverFlow – 一个秘密武器
2010-09-25 12:51:00
![](https://img.aspxhome.com/file/UploadPic/20109/25/rss1-42s.png)