SoFunction
Updated on 2024-11-21

Reading and writing data in xlsx format using python+pandas

Use the pandas library to read data in xlsx format.

Data in excel:

Example code 1:

import pandas as pd
 
# data = pd.read_excel('. /data/medical-examination-form.xlsx')
# data = pd.read_excel('. /data/Medical Examination Form.xlsx', sheet_name='Sheet1')
data = pd.read_excel('. /data/medical-examination-form.xlsx', sheet_name=0)
print(data)
 
print("*" * 100)
 
data = pd.read_excel('. /data/medical-examination-form.xlsx', sheet_name=0, header=0, usecols=[1, 2, 4])
"""
sheet_name: return the specified sheet, if sheet_name is specified as None, then return the whole sheet, if you need to return more than one sheet, you can specify sheet_name as a list, such as ['sheet1', 'sheet2'].
header: the header of the specified data table, default value is 0, i.e. the first line as the header.
usecols: read the specified columns, for example, want to read the first column and the second column data
"""
print(data)

Run results:

Example code 2: [Modify data in xlsx

import pandas as pd
from pandas import DataFrame
 
data = pd.read_excel('. /data/medical-examination-form.xlsx', sheet_name='Sheet1')
print(data)
# Change male to the number 0 and female to the number 1 in gender
data['Gender'][data['Gender'] == 'Male'] = 0
data['Gender'][data['Gender'] == 'Female'] = 1
print(data)
 
"""
Note: Here the data for a copy of the excel data, the data to modify and will not directly affect our original excel, must be saved after the modification to be able to modify the excel.
"""
# The following code will create a new file and overwrite the entire file if it exists, similar to 'w' mode
# DataFrame(data).to_excel('. /data/medical-examination-form', sheet_name='Sheet1', index=False, header=True)
data.to_excel('. /data/medical-examination-form', sheet_name='Sheet1', index=False, header=True)

Run results:

to this article on the use of python + pandas read and write xlsx format data in the article is introduced to this, more related pandas read and write xlsx data content, please search for my previous posts or continue to browse the following related articles I hope you will support me in the future!