python-pandas使用

 写excel

import pandas as pd
"""
pandas学习
"""

true = True
false = False
none = None
null =None
datas = [
            {
                "customerCategoryCode": "1002",
                "customerCategoryId": "6U58C261UR70027",
                "customerCategoryIsLeaf": true,
                "customerCategoryName": "B类客户",
                "revenueAmount": 11111.1
            },
            {
                "customerCategoryCode": "1001",
                "customerCategoryId": "6U58C261UR70026",
                "customerCategoryIsLeaf": true,
                "customerCategoryName": "A类客户",
                "revenueAmount": 5555.55
            }
        ]
#将字典列表转换为DataFrame
pf = pd.DataFrame(datas)
print(pf)
print(pf["customerCategoryName"])

# 指定字段内容和顺序
order = ["revenueAmount","customerCategoryName","customerCategoryCode"]
pf = pf[order]
print(pf)

#重命名表头
columns_map = {
    "revenueAmount":"金额",
    "customerCategoryName":"客户类型",
    "customerCategoryCode":"编号"
}
pf.rename(columns=columns_map,inplace=True)
print(pf)

#输出行号
for j in pf.index:
    print(f"行号:{j}")

#插入列   , value=a   、 value=['a','b']
for i, value in enumerate(order):
    pf.insert(2 * i, f'表头{value}', ['a','b'])
print(pf)

# for i, value in enumerate(order):
# columns = [f'[{j}].{value}' for j in pf.index]
# pf.insert(2 * i, f'表头{value}', columns)
# print(pf)

#输出excel pf.to_excel('0208.xlsx',sheet_name='sheet',encoding = 'utf-8',index = False) def export_excel(export,excel_name): """ 将字典列表导出为Excel文件的方法 :param export: 字典列表 :param excel_name: excel名称 :return: """ # 将字典列表转换为DataFrame pf = pd.DataFrame(list(export)) # 指定字段顺序 order = ['caseid','page','casename','target','targetKey','expect','actual','result'] pf = pf[order] columns_map = { 'caseid': '用例id', 'page': '页面', 'casename': '用例名称', 'target': '指标', 'targetKey': '指标key', 'expect': '期望值', 'actual': '实际值', 'result': '结果'} #重命名表头 pf.rename(columns=columns_map,inplace=True) # 指定生成的Excel表格名称 file_path = pd.ExcelWriter(excel_name) #替换空单元格 pf.fillna(' ',inplace = True) #输出 pf.to_excel(file_path,sheet_name='sheet',encoding = 'utf-8',index = False) #保存 file_path.save()

 读excel

posted @ 2023-02-08 14:22  南方的墙  阅读(19)  评论(0编辑  收藏  举报