Pandas 读取 Excel 斜着读

读取 Excel 斜着读数据

python 复制代码
import pandas as pd


def read_sideling(direction, sheet_name, row_start, col_start, gap):
    """
    斜着读数据
    :param sheet_name:
    :param direction: left 往左下方读取 ↙,right 往右下方读取 ↘
    :param row_idx:  行号,从0开始,
    :param col_idx:  列号,从0开始
    :return:
    """
    # header=None 没有标题行
    df = pd.read_excel("222.xlsx", sheet_name=sheet_name, header=None)
    step = gap + 1
    total = 0
    continuous = 5  # 连续几连,算有效值
    col_idx = col_start  # 第一次,列号=传入的值
    # 如果3行3行的比,再在上面套一层 for
    for row_idx in range(row_start, step * continuous + 1, step):  # range(1, 4) = 1~3 逗号右边是小于,所以 < 4 ,是 1~3,不包括4
        if row_idx == 0 :
            # 如果指定的行是从0开始,就跳过,否则不用跳过
            continue  # 跳过第1行
        # print(row)
        val = df.iloc[row_idx, col_idx]  # 指定行,列
        # TODO 判断 1
        # if val != 1:
        #     print("第%s行,第%s列  =>  %s" % (row_idx + 1, col_idx, val))
        #     break  # 三行数据,有一个不等于 1 就跳过
        total = total + 1
        # 列号位移
        if direction == "right":
            # 从右往左,列的序号 加 1
            col_idx = col_idx + 1
        if direction == "left":
            # 从右往左,列的序号 减 1
            col_idx = col_idx - 1
        print("第%s行,第%s列 =>  %s" % (row_idx + 1, col_idx, val))
    # 三行数据都 =1
    if total == continuous:
        # 'a' 追加到文件中, 'w' 以前的数据不要了,每次都重写
        write_val = df.iloc[0, col_idx]
        print("达到连续三个1,将值写文件%s" % write_val)
        with open('output.txt', 'a', encoding='utf-8') as json_file:
            json_file.write(str(write_val) + " ")  # 把最上面的值写到文件中
    else:
        print("没达到三个1 不写文件")


# 斜着读数据,如果要和竖着的一起处理,就把方法复制到一个文件中
if __name__ == '__main__':
    # ritht 向台
    read_sideling(direction='right', sheet_name=0, row_start=1, col_start=1, gap=0)
    # left 向左
    read_sideling(direction='left', sheet_name=0, row_start=1, col_start=10, gap=0)
    # left 向左
    read_sideling(direction='left', sheet_name=0, row_start=1, col_start=14, gap=2)
相关推荐
慕婉03076 小时前
Pandas 核心数据结构详解:Series 和 DataFrame 完全指南
数据结构·pandas
是紫焅呢21 小时前
N数据分析pandas基础.py
python·青少年编程·数据挖掘·数据分析·pandas·学习方法·visual studio code
摘取一颗天上星️4 天前
机器学习四剑客:Numpy、Pandas、PIL、Matplotlib 完全指南
机器学习·numpy·pandas
Python当打之年4 天前
【61 Pandas+Pyecharts | 基于Apriori算法及帕累托算法的超市销售数据分析可视化】
python·信息可视化·数据分析·pandas·数据可视化
Python当打之年4 天前
【59 Pandas+Pyecharts | 淘宝华为手机商品数据分析可视化】
华为·智能手机·数据分析·pandas·数据可视化
Python当打之年5 天前
【62 Pandas+Pyecharts | 智联招聘大数据岗位数据分析可视化】
大数据·python·数据分析·pandas·数据可视化
liuweidong08025 天前
【Pandas】pandas DataFrame replace
pandas
一晌小贪欢5 天前
【Python办公】使用pandas批量读取csv保存为Excel
python·excel·pandas·读取excel·python办公·excel转csv