How to read data in python

(*-*)浩
Release: 2019-06-24 11:02:47
Original
7366 people have browsed it

Reading data can facilitate our work. There are many common ways to read data in python. So how does python read data?

How to read data in python

Use the read_csv module in pandas to read the data directly.(Recommended learning:Python video tutorial)

data = pd.read_csv('/home/nw/Desktop/dataset/iris.txt',header = None)
Copy after login

In the above code, the first part of read_csv is the path where the data set is stored. The following header is very important. I often think that the header is missing. , the total amount of data is reduced by 1, because the missing row of data becomes the column index in the DataFrame.

There is also a more traditional method, which is to open the file directly with open and take out the information in the file first. No matter what it looks like, take it out first and then talk about what you want to do. Just process the extracted variables.

f= open('/home/nw/Desktop/dataset/iris.txt','rb') dataset = pickle.load(f) #这种方法适用于自己存取自己的数据,有时候在读取别人的数据的时候是不行的,因为别人存数据的方式不一定是用pickle.dump的方 ##式存数据的。 f = open('/home/nw/Desktop/dataset/iris.txt') ''' 注意这里的open后面最好不要加上其他的读取方式,不需要‘rb’之类的读取方式。因为在后续的数据处理中可能还需要将二进制的数 据转换成自己想要的个数。 ''' lines = f.readlines() ''' 现在lines中已经包含了所有的数据信息,我们想要得到的数据格式都可以基于lines做处理。如我读出的iris数据格式是一个列表的形 式,使用len(lines)得到列表中元素的个数是151,打印出lines,可以看到lines中每个元素都是一个字符串,并且每个字符串后面都 有'\n'的换行字符,最后一行是空行,所以最后一行是多余,并且要去掉每行中的'\n' ''' arr = [] for i in range(len(lines)): if lines[i] != '\n': arr.append(lines[i]) for i in range(len(arr)): arr[i] = arr[i].strip('\n')#将每行的'\n'脱去
Copy after login

For more Python related technical articles, please visit thePython Tutorialcolumn to learn!

The above is the detailed content of How to read data in python. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!