Python | Read csv using pandas.read_csv()
To access data from the CSV file, we require a function read_csv() that retrieves data in the form of the Dataframe.
Syntax of read_csv()
Syntax: pd.read_csv(filepath_or_buffer, sep=’ ,’ , header=’infer’, index_col=None, usecols=None, engine=None, skiprows=None, nrows=None)
- filepath_or_buffer: It is the location of the file which is to be retrieved using this function. It accepts any string path or URL of the file.
- sep: It stands for separator, default is ‘, ‘ as in CSV(comma separated values).
- header: It accepts int, a list of int, row numbers to use as the column names, and the start of the data. If no names are passed, i.e., header=None, then, it will display the first column as 0, the second as 1, and so on.
- usecols: It is used to retrieve only selected columns from the CSV file.
- nrows: It means a number of rows to be displayed from the dataset.
- index_col: If None, there are no index numbers displayed along with records.
- skiprows: Skips passed rows in the new data frame.
Read CSV using Pandas read_csv
Before using this function, we must import the Pandas library, we will load the CSV file.
Example 1: Using sep in read_csv()
In this example, we will manipulate our existing CSV file and then add some special characters to see how the sep parameter works.
Example 2: Using usecols in read_csv()
Here, we are specifying only 3 columns,i.e.[“tip”, “sex”, “time”] to load and we use the header 0 as its default header.
Example 3: Using index_col in read_csv()
Here, we use the “sex” index first and then the “tip” index, we can simply reindex the header with index_col parameter.
Example 4: Using nrows in read_csv()
Here, we just display only 5 rows using nrows parameter.
Example 5: Using skiprows in read_csv()
The skiprows help to skip some rows in CSV, i.e, here you will observe that the upper row and the last row from the original CSV data have been skipped.