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)
相关推荐
小大宇21 小时前
python pandas dataFrame sqlAlchemy案例
python·pandas
chouchuang2 天前
day-040-Pandas可视化与实战
pandas
chouchuang5 天前
day-037-Pandas数据读取
pandas
benchmark_cc6 天前
如何用 Python 进行多周期 K 线合成与时区对齐?基于 QuantDash 与 Pandas 的量化数据清洗实战(附 GitHub 源码)
开发语言·python·github·盯盘·pandas·quantdash·量化数据
梅雅达编程笔记8 天前
零基础学 Python 第14章 | 模块、包与第三方库
开发语言·python·django·numpy·pandas
梅雅达编程笔记8 天前
零基础学 Python 第15章 | 类与对象:面向对象编程入门
开发语言·python·django·numpy·pandas
benchmark_cc8 天前
Python 量化核心基础:前复权、后复权与不复权有什么区别?基于 QuantDash 的数据处理与回测避坑指南
开发语言·python·pandas·量化策略·量化交易·quantdash
人工干智能9 天前
科普:Pandas 索引器 loc 与 iloc 的编程思维
java·人工智能·pandas
梅雅达编程笔记9 天前
编程启蒙|Scratch 转 Python 系列第9天:字典/哈希表积木双向对照(AI大模型参数配置表实战)
开发语言·人工智能·python·numpy·pandas
benchmark_cc9 天前
用 Streamlit + QuantDash 10分钟拼装一个跨市场持仓风险与相关性诊断面板
开发语言·python·pandas·量化策略·量化交易·quantdash