YouTip LogoYouTip

Pandas Csv File

CSV (Comma-Separated Values, sometimes also called character-separated values because the separator can also be not a comma), its file stores tabular data (numbers and text) in plain text form. CSV is a common, relatively simple file format, widely used by users, businesses, and science. Pandas can easily process CSV files, the common methods are: | **Method Name** | **Function Description** | **Common Parameters** | | --- | --- | --- | | `pd.read_csv()` | Read data from CSV file and load as DataFrame | `filepath_or_buffer` (path or file object), `sep` (separator), `header` (row header), `names` (custom column names), `dtype` (data type), `index_col` (index column) | | `DataFrame.to_csv()` | Write DataFrame to CSV file | `path_or_buffer` (target path or file object), `sep` (separator), `index` (whether to write index), `columns` (specify columns), `header` (whether to write column names), `mode` (write mode) | This article takes [nba.csv](https://static.jyshare.com/download/nba.csv) as an example, you can [download nba.csv](https://static.jyshare.com/download/nba.csv) or [open nba.csv](https://static.jyshare.com/download/nba.csv.txt) to view. ### pd.read_csv() - Read CSV File read_csv() is the main method to read data from a CSV file, loading the data as a DataFrame. ```python import pandas as pd # Read CSV file, and customize column names and delimiter df = pd.read_csv('data.csv', sep=';', header=0, names=['A', 'B', 'C'], dtype={'A': int, 'B': float}) print(df) read_csv Common Parameters: | **Parameter** | **Description** | **Default Value** | | --- | --- | --- | | `filepath_or_buffer` | Path or file object of the CSV file (supports URL, file path, file object, etc.) | Required parameter | | `sep` | Define the field separator, default is comma (`,`), can be changed to other characters such as tab (`t`) | `','` | | `header` | Specify the row number as the column title, default is 0 (first row), or set to `None` for no header | `0` | | `names` | Custom column names, pass a list of column names | `None` | | `index_col` | Column number or column name to use as row index | `None` | | `usecols` | Read specified columns, can be column names or column indices | `None` | | `dtype` | Force conversion of column to specified data type | `None` | | `skiprows` | Skip the specified number of rows at the beginning of the file, or pass a list of row numbers | `None` | | `nrows` | Read the first N rows of data | `None` | | `na_values` | Specify which values should be treated as missing values (NaN) | `None` | | `skipfooter` | Skip the specified number of rows at the end of the file | `0` | | `encoding` | File encoding format (such as `utf-8`, `latin1`, etc.) | `None` | Read nba.csv file data: ## Example ```python import pandas as pd df = pd.read_csv('nba.csv') print(df.to_string()) to_string() is used
← Func Array Key FirstPython Urllib β†’