python读取.data文件的实现
作者:青青木屋 时间:2021-10-28 06:24:05
.data文件格式
.data文件是用来存储数据的一种文件格式。之前通常数据是用逗号隔开或tab健隔开的格式,现在也可能是文本文件格式或二进制文件格式。
识别.data文件里面的数据
1、先测试一下文件是文本文件还是二进制文件
用网上可以下载到的iris.data文件来举例(iris.data文件下载地址:https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data),代码如下:
# 通过python自带的文件读取文本文件
file=open('iris.data','r')
data=file.read()
print(data)
file.close()
运行之后,可以看到结果(此处放部分数据结果):
根据打印出来的数据结果,可以分析出来,iris.data存的是文本数据,并且是用逗号分隔的,也可以认为是csv文件格式。
如果打印出来的数据结果不是文本类型的话,可以测试一下是不是二进制文件,代码如下:
# 通过python自带的文件读取二进制文件
file=open('iris.data','rb')
data=file.read()
print(data)
file.close()
2、用Pandas读取.data文件
方法如下:
用read_csv()方法读取文件,这个方法会自动创建一个dataframe,将数据转换进去,代码如下:
# 使用Pandas读取数据
import pandas as pd
data=pd.read_csv('iris.data',header=None,sep=',')
print(data)
注意:在第一步里面查看文件内容的时候,发现iris.data文件里面没有表头,iris.data的表头是在iris.names文件里面进行说明的(附上iris.names文件下载地址:https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.names),所以在read_csv函数调用的时候,需要加上header=None,否则data里面的第一行就会自动变成表头,这样的话150行数据就变成149行。
运行之后,显示结果如下:
3、其他数据存储类型
除了上述提到的文件格式外,还有json格式和pickle。
在读取的时候,需要import json和import pickle后,调用json.dumps()方法和pickle.dump()方法进行读取。
参考资料
https://www.askpython.com/python/examples/read-data-files-in-python
来源:https://blog.csdn.net/greenqingqingws/article/details/128906287
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
pyCaret效率倍增开源低代码的python机器学习工具
![](https://img.aspxhome.com/file/2023/3/112613_0s.png)
python定时关机小脚本
Python实现读取字符串按列分配后按行输出示例
Python torch.flatten()函数案例详解
Pycharm 如何设置HTML文件自动补全代码或标签
![](https://img.aspxhome.com/file/2023/3/121473_0s.png)
python学习实操案例(二)
![](https://img.aspxhome.com/file/2023/8/112738_0s.png)
python使用Queue在多个子进程间交换数据的方法
关于asp分页的新想法
单步调试 step into/step out/step over 区别说明
![](https://img.aspxhome.com/file/2023/9/115629_0s.jpg)
使用Python制作一个简易的远控终端
![](https://img.aspxhome.com/file/2023/2/118002_0s.png)
python算法题 链表反转详解
![](https://img.aspxhome.com/file/2023/1/92201_0s.jpg)
Python Websocket服务端通信的使用示例
![](https://img.aspxhome.com/file/2023/8/110018_0s.png)
PL/SQL number型数据
MySQL 数据库语句优化的原则
python库sklearn常用操作
Python多线程爬取豆瓣影评API接口
asp无限级分类加js收缩伸展功能代码
python类装饰器用法实例
Pytorch.nn.conv2d 过程验证方式(单,多通道卷积过程)
![](https://img.aspxhome.com/file/2023/0/97720_0s.jpg)
python seaborn heatmap可视化相关性矩阵实例
![](https://img.aspxhome.com/file/2023/0/101450_0s.jpg)