Introduction
We use read_excel to open and read data stored in Excel files so we can analyze it in Python.
We use read_excel to open and read data stored in Excel files so we can analyze it in Python.
pandas.read_excel(io, sheet_name=0, header=0, usecols=None)
io is the file path or Excel file object.
sheet_name chooses which sheet to read; default is the first sheet.
import pandas as pd df = pd.read_excel('data.xlsx')
df = pd.read_excel('data.xlsx', sheet_name='Sales')
df = pd.read_excel('data.xlsx', usecols='A:C')
This code first creates a small Excel file with sample data, then reads it back into Python and prints it.
import pandas as pd # Create a sample Excel file sample_data = {'Name': ['Alice', 'Bob', 'Charlie'], 'Age': [25, 30, 35], 'City': ['NY', 'LA', 'Chicago']} df_sample = pd.DataFrame(sample_data) df_sample.to_excel('sample.xlsx', index=False) # Read the Excel file read_df = pd.read_excel('sample.xlsx') print(read_df)
Make sure you have the openpyxl package installed to read .xlsx files.
You can read multiple sheets by passing a list to sheet_name.
read_excel loads Excel data into a DataFrame for easy analysis.
You can select sheets and columns to read only the data you need.
This is useful to work with Excel data directly in Python without manual copying.
pandas.read_excel() function do in Python?read_excelpandas.read_excel() is designed to load data from Excel files into Python as a DataFrame.to_excel() or to_csv(), not read_excel().read_excel loads Excel data [OK]read_excel is sheet_name, not sheet or sheetname.sheet_name to select sheet [OK]import pandas as pd
df = pd.read_excel('data.xlsx', usecols='A:C')
print(df.columns.tolist())usecols='A:C' selects columns A to C from the Excel file, which correspond to the columns named 'Name', 'Age', and 'City'.df.columns contains the actual column names from the Excel file, so printing df.columns.tolist() outputs ['Name', 'Age', 'City'].import pandas as pd
df = pd.read_excel('data.xlsx', sheet_name=1, usecols=[0, 2, 5])sheet_name=1 is valid to select the second sheet by index (0-based), so this is not an error cause.[0, 2, 5] is valid to select columns by zero-based index, so this is not an error cause.sheet_name, and to select columns by name is usecols with a list of column names.sheet_name='2023' and usecols=['Date', 'Sales', 'Profit'], which is the correct syntax to read only those columns from the specified sheet.sheet and columns. pd.read_excel('report.xlsx', sheet_name='2023', usecols='Date,Sales,Profit') uses a string for usecols which is invalid for column names. pd.read_excel('report.xlsx', sheet_name='2023', usecols=[0,1,2]) selects columns by index, not by name.sheet_name and list in usecols for named columns [OK]Pass the test and this pattern moves unknown