Bootstrap

python中Pandas操作excel补全内容

补全ID、InStore、Date

import random
from datetime import datetime, timedelta

import pandas as pd

file_path = r"C:\Users\xb\Desktop\Books_1.xlsx"
books = pd.read_excel(io=file_path, skiprows=3, usecols="C:F", dtype={"ID": str, "InStore": str,"Date":str})
rangeIndex = books.index
YN = ["yes", "no"]

# 定义时间范围
start_date = datetime(2020, 1, 1)
end_date = datetime(2024, 1, 1)
time_range = (end_date - start_date).days

for i in rangeIndex:
    books.at[i, "ID"] = i + 1
    c = YN[random.randint(0, 1)]
    books.at[i, "InStore"] = str(c)

    # 生成随机日期
    random_date = start_date + timedelta(days=random.randint(0, time_range))
    books.at[i, "Date"] = random_date.strftime("%Y/%m/%d")  # 格式化日期

print(books)

在这里插入图片描述

;