Home  >  Article  >  Backend Development  >  Use pandas to read the first few lines specified in the csv file

Use pandas to read the first few lines specified in the csv file

不言
不言Original
2018-04-20 14:12:377069browse

The following is an article about using pandas to read the first few lines specified in a csv file. It has a good reference value and I hope it will be helpful to everyone. Let’s take a look together

The csv file used to store data sometimes has a very large amount of data. However, sometimes we don’t need all the data. What we need may only be the first few lines.

This can be achieved through the function of reading the specified number of rows in read_csv in pandas.

For example, there is a data.csv file. The content of the file is as follows:

GreydeMac-mini:chapter06 greyzhang$ cat data.csv 
,name_01,coment_01,,,,
2,name_02,coment_02,,,,
3,name_03,coment_03,,,,
4,name_04,coment_04,,,,
5,name_05,coment_05,,,,
6,name_06,coment_06,,,,
7,name_07,coment_07,,,,
8,name_08,coment_08,,,,
9,name_09,coment_09,,,,
10,name_10,coment_10,,,,
11,name_11,coment_11,,,,
12,name_12,coment_12,,,,
13,name_13,coment_13,,,,
14,name_14,coment_14,,,,
15,name_15,coment_15,,,,
16,name_16,coment_16,,,,
17,name_17,coment_17,,,,
18,name_18,coment_18,,,,
19,name_19,coment_19,,,,
20,name_20,coment_20,,,,
21,name_21,coment_21,,,,

If The data we need is only the first 5 rows, so the reading method can be specified by nrows. Write the code as follows:

 1 #!/usr/bin/python
 2 
 3 import pandasas pd
 4 
 5 data = pd.read_csv('data.csv',nrows =5)
 6 print(data)
 7

The running result of the code is as follows:

GreydeMac-mini:chapter06 greyzhang$ python row_test.py 
 Unnamed: 0 name_01 coment_01 Unnamed: 3 Unnamed: 4 Unnamed: 5 \
0   2 name_02 coment_02   NaN   NaN   NaN 
1   3 name_03 coment_03   NaN   NaN   NaN 
2   4 name_04 coment_04   NaN   NaN   NaN 
3   5 name_05 coment_05   NaN   NaN   NaN 
4   6 name_06 coment_06   NaN   NaN   NaN 
 Unnamed: 6 
0   NaN 
1   NaN 
2   NaN 
3   NaN 
4   NaN 
GreydeMac-mini:chapter06 greyzhang$

As can be seen from the above results, the expected function is achieved by specifying the number of rows to be read.

Related recommendations:

pandas implementation of selecting rows at a specific index

##

The above is the detailed content of Use pandas to read the first few lines specified in the csv file. 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