import pandas as pd
from datetime import date,timedelta
import time
# 月份累加
def add_month(d, md):
yd = md // 12 # 整除
m = d.month + md % 12
if m != 12:
yd += m // 12
m = m % 12
return date(d.year + yd, m, d.day)
if __name__ == '__main__':
# 1.0 读取文件
path = "C:/Users/123/Desktop/pandas/004_数据区域读取_填充数字/"
file = "Books.xlsx"
book = pd.read_excel(path + file, skiprows=3, usecols="C:G", index_col=None,
dtype={"ID":str, "InStore":str, "Date":str, "StrNum":str})
print(book)
# 2.0 操作文件
start = date(2018, 1, 20) # 设置时间
# 方法一
# for i in book.index:
# book["ID"].at[i] = i + 1
# book["InStore"].at[i] = "Yes" if i % 2 == 0 else "No"
# month = add_month(start, i) # 累加月份
# book["Date"].at[i] = month + timedelta(days=i) # 累加天数
# book["StrNum"].at[i] = "str" + str(i) # 字符串 + 数字
# 方法二
for i in book.index:
book.at[i, "ID"] = i + 1
book.at[i, "InStore"] = "Yes" if i % 2 == 0 else "No"
month = add_month(start, i) # 累加月份
book.at[i, "Date"] = month + timedelta(days=i) # 累加天数
book.at[i, "StrNum"] = "str" + str(i) # 字符串 + 数字
print(book)
book.set_index("ID", inplace=True)
# 3.0 输入文件
file_write = "Books_v2.xlsx"
book.to_excel(path + file_write)
print("Done!")