How to read a CSV file using the Python pandas library
Here is an example of how to read a CSV file using the Python pandas library:
import pandas as pd
# Read the CSV file into a DataFrame
df = pd.read_csv('file.csv')
# Print the first few rows of the DataFrame
print(df.head())
This will read the CSV file into a Pandas DataFrame, which is a 2-dimensional size-mutable tabular data structure with rows and columns. The head()
method is used to print the first few rows of the DataFrame.
If the CSV file has a header row, it will be used as the column names for the DataFrame. If the file does not have a header row, you can specify the column names by passing a list of strings to the names
parameter:
df = pd.read_csv('file.csv', names=['col1', 'col2', 'col3'])
There are many other optional parameters that can be used to customize the reading of the CSV file. For example, you can specify the delimiter used in the file with the sep
parameter, or specify that certain rows should be skipped with the skiprows
parameter. You can find more information about these and other parameters in the pandas documentation.
Leave a Comment