You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

不依赖numpy/pandas,用基础Python判断数据列趋势的方法

纯Python实现列趋势判断(无外部依赖)

需要实现一个不依赖NumPy、Pandas等外部库的Python脚本,判断以下表格中每一列的趋势为上升(Upward)、恒定(Constant)或下降(Downward)。

输入数据

-Column1--Column2--Column3--Column4-
98394112 78677690 20070400 134579200
98418688 78684002 20070400 134554624
98418688 78692194 20070400 134554624
98443264 78708578 20070400 134530048
98443264 78724962 20070400 134530048
98467840 78733154 20070400 134505472
98467840 78749538 20070400 134505472
98516992 78774114 20070400 134456320
98516992 78798690 20070400 134456320
98566144 78831458 20070400 134407168
98615296 78864226 20070400 134358016
98615296 78888802 20070400 134358016

实现代码

def determine_column_trends(data_text):
    # 拆分并清理行数据
    lines = [line.strip() for line in data_text.split('\n') if line.strip()]
    # 提取列名并清理符号
    headers = [h.strip('-') for h in lines[0].split('--') if h.strip()]
    # 转换数据行为整数列表
    data_rows = []
    for line in lines[1:]:
        row = list(map(int, line.split()))
        data_rows.append(row)
    # 将行数据转置为列数据
    columns = list(zip(*data_rows))
    
    trends = {}
    for col_name, col_data in zip(headers, columns):
        has_increase = False
        has_decrease = False
        # 遍历相邻元素判断升降
        for i in range(1, len(col_data)):
            prev_val = col_data[i-1]
            curr_val = col_data[i]
            if curr_val > prev_val:
                has_increase = True
            elif curr_val < prev_val:
                has_decrease = True
        # 确定最终趋势
        if has_increase and not has_decrease:
            trends[col_name] = 'Upward'
        elif has_decrease and not has_increase:
            trends[col_name] = 'Downward'
        else:
            trends[col_name] = 'Constant'
    return trends

# 传入输入数据并输出结果
input_data = """-Column1--Column2--Column3--Column4-
98394112 78677690 20070400 134579200
98418688 78684002 20070400 134554624
98418688 78692194 20070400 134554624
98443264 78708578 20070400 134530048
98443264 78724962 20070400 134530048
98467840 78733154 20070400 134505472
98467840 78749538 20070400 134505472
98516992 78774114 20070400 134456320
98516992 78798690 20070400 134456320
98566144 78831458 20070400 134407168
98615296 78864226 20070400 134358016
98615296 78888802 20070400 134358016"""

result = determine_column_trends(input_data)
for col, trend in result.items():
    print(f"{col}: {trend}")

代码说明

  1. 数据解析:拆分输入文本,清理无效行,提取并格式化列名,将数据行转换为整数列表。
  2. 列数据转换:通过zip(*data_rows)实现行转列,方便按列处理数据。
  3. 趋势判断逻辑:遍历每一列的相邻元素,标记是否出现上升或下降:
    • 仅存在上升 → 标记为Upward
    • 仅存在下降 → 标记为Downward
    • 两者都存在或全无 → 标记为Constant

输出结果

Column1: Upward
Column2: Upward
Column3: Constant
Column4: Downward

内容的提问来源于stack exchange,提问作者Susanta Dutta

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 22:50:39