python excel数据转为字典格式的两种方法

 话不多说,直接看代码;

这是excel原数据:

 转换成的效果数据(首行为字典的“键”,其余行对应为对应的“值”):

{'Line': 'HG16A', 'Station': 'AT_Audio', 'GroupName': 'AL5626_FA', 'PN': '%', 'Status': '1MM', 'userid': 167942, 'TransDateTime': 20210309133940}
{'Line': 'HG16A', 'Station': 'AT_Audio', 'GroupName': 'AL5626_FA', 'PN': '%', 'Status': 'A4', 'userid': 167942, 'TransDateTime': 20210309133941}
{'Line': 'HG16A', 'Station': 'AT_Audio', 'GroupName': 'AL5626_FA', 'PN': '%', 'Status': 'RAUD', 'userid': 167942, 'TransDateTime': 20210309133941}
{'Line': 'HG16A', 'Station': 'AT_MMI_Auto', 'GroupName': 'AL5626_FA', 'PN': '%', 'Status': 7, 'userid': 167942, 'TransDateTime': 20210309133941}

path_file_name:文件路径名称:

我的这个参数是:

"C:\Users\Administrator\Desktop\line_data.xlsx"

方法1:

    @staticmethod
    def read_excel_list(path_file_name):  # Return 字典格式数据
        excel_data = pd.read_excel(path_file_name)
        one_row_keys = excel_data.keys()  # 读取出来的首行数据
        row_keys = [i for i in one_row_keys]  # 首行遍历形成的列表格式
        sum_rows = excel_data.index.values  # 读取所有行数形成列表
        df_list = []
        for i in sum_rows:  # 遍历所有行号
            # loc为按列名索引 iloc 为按位置索引,使用的是 [[行号], [列名]]
            row_dict = excel_data.loc[i, row_keys].to_dict()  #
            df_list.append(row_dict)
        return df_list

方法2:

    @staticmethod
    def read_excel_list_plus(path_file_name):  # Return 字典格式数据
        excel_data = pd.read_excel(path_file_name)
        rows, cols = excel_data.shape  # 行数 列数
        print(excel_data.columns)  # 读取第一行表头,返回的是所有行的表头列表
        print(excel_data.columns[2])  # 读取第一行表头,第二列 字段名字
        print(excel_data["Line"][0])  # 读取 Line列 第0行
        df_list = []
        for i in range(0, rows):  # 遍历所有行
            dict_data = {}
            for j in excel_data.columns:  # 遍历第一行表头
                dict_data[j] = excel_data[j][i]  # 形成字典键值对
            df_list.append(dict_data)  # 添加进字典
        return df_list

运行效果如图:

就得到对应的字典格式数据啦

 

  • 4
    点赞
  • 31
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值