Reading CSV and TXT files

read_csv is the go-to method for reading CSV files in pandas. It can also be used to read txt files. The syntax of using read_csv is shown in the following code:

pd.read_csv(filepath, sep=', ', dtype=None, header=None, names=None, skiprows=None, index_col=None, skip_blank_lines=TRUE, na_filter=TRUE)

The parameters of the read_csv method are as follows:

  • filepath: A string or filename with or without a filepath.
  • dtype: Can be passed as a dictionary containing name and type as a key-value pair. Specifies the data type of the column name. Generally, pandas guesses the type of columns based on the first few rows.
  • header: True/False. This specifies whether the first row in the data is a header or not.
  • names: List. Specifies column names for all the columns of a dataset.
  • skiprows: List. Skip certain rows of data by specifying row indices.
  • index_col: Series/List. Specifies the column that can work as a row number/identifier.
  • skip_blank_lines: True/False. Specifies whether to skip blank lines or not.
  • na_filter: True/False. Specifies whether to filter NA values or not.
  • usecols: List. Returns the subset of data with columns in the passed list.

The read_csv method returns a DataFrame. The following are some examples of reading files using the read_csv method.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset