Home  >  Article  >  Backend Development  >  How to read data in python

How to read data in python

(*-*)浩
(*-*)浩Original
2019-06-24 11:02:477446browse

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)

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'脱去

For more Python related technical articles, please visit the Python Tutorial column 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!

Statement:
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