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)
相关推荐
Pyeako2 天前
python中pandas库的使用(超详细)
开发语言·python·pandas
ranchor6663 天前
excel+pandas使用str.contains() 的典型例子
excel·pandas
啊巴矲3 天前
小白从零开始勇闯人工智能:机器学习初级篇(pandas库)
人工智能·机器学习·pandas
Keep__Fighting4 天前
【机器学习:集成算法】
人工智能·算法·机器学习·pandas·集成学习·sklearn
Hi_kenyon4 天前
Pandas Cheatsheet I
python·pandas
万粉变现经纪人4 天前
如何解决 pip install 网络报错 403 Forbidden(访问被阻止)问题
数据库·python·pycharm·beautifulsoup·bug·pandas·pip
咚咚王者4 天前
人工智能之数据分析 Pandas:第十一章 项目实践
人工智能·数据分析·pandas
咚咚王者4 天前
人工智能之数据分析 Pandas:第十章 知识总结
人工智能·数据分析·pandas
编程设计3665 天前
pandas 中 DataFrame、mean()、groupby 和 fillna 函数的核心作用
机器学习·数据挖掘·pandas
咚咚王者5 天前
人工智能之数据分析 Pandas:第九章 性能优化
人工智能·数据分析·pandas