Python Excel Pandas

作者: 望月成三人 | 来源:发表于2021-09-23 18:06 被阅读0次
    import pandas as pd
    from ast import literal_eval
    
    
    class OperateExcel():
        def __init__(self, file_path):
            self.file_path = file_path
            self.df = pd.read_excel(file_path, sheet_name="Sheet1")  # sheet_name不指定时默认返回全表数据
            # self.df = pd.read_excel(file_path, sheet_name="Sheet1", usecols=['name', 'method'])
    
        def get_excel(self):
            """
             读取表格数据存为json
            :return: 
            """
    
            data = []
            for i in self.df.values:
                params = ""
                if i[3] == "post":
                    params = literal_eval(i[4])
                app = {"id": i[0], "name": i[2], "method": i[3], "params": params}
                data.append(app)
            print(data)
    
        def write_excel(self):
            # 根据条件累加数据
            self.df['id'][self.df['name'] == '测试2'] += 100
            print(self.df.head())
            self.df.to_excel('data3.xlsx', sheet_name='Sheet1', index=False, header=True)
    
            # 新增一行
            self.df.loc[10] = [5, 'Eric', 'male', 20, '']
    
            # 新增一列
            self.df['favorite'] = None
    
            self.df.to_excel('data3.xlsx', sheet_name='Sheet1', index=False, header=True)
            print(self.df.head())
    
        def get_filter_excel(self):
            # 查看所有的值
            print(self.df.values)
    
            # 查看第一行的值
            print(self.df.values[0])
    
            # 查看某一列所有的值
            print(self.df['name'].values)
            print("===打印头部数据,仅查看数据示例时常用====")
            print(self.df.head())
            print("====打印列标题===")
            print(self.df.columns)
            print("====打印行========")
            print(self.df.index)
            print("========打印指定列============")
            print(self.df["name"])
    
    
    if __name__ == "__main__":
        file_path = 'data3.xlsx'
        o_excel = OperateExcel(file_path)
        o_excel.get_excel()
        # o_excel.write_excel()
        # o_excel.get_filter_excel()
    
    
    • excel文件内容
    image.png
    • 其他几款操作excel对比,图片来源这里
      image.png

    相关文章

      网友评论

        本文标题:Python Excel Pandas

        本文链接:https://www.haomeiwen.com/subject/ulpogltx.html