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

使用Pandas定位DataFrame最大值对应X轴位置的报错排查

解决Pandas批量处理CSV时的TypeError: reduction operation 'argmax' not allowed for this dtype问题

问题场景

使用Pandas和glob批量处理指定文件夹内的CSV文件,目标是找出4个列范围的最大值,并获取最大值对应的X轴行值。运行代码时触发TypeError,报错指向df1.idxmax(axis=1).idxmax()这一行。

报错原因

  1. 数据类型不兼容:部分CSV的目标列范围中存在非数值类型数据(如字符串),导致idxmax无法执行argmax运算。
  2. NaN判断逻辑错误:用str(taree)=='nan'判断空值,无法正确识别Pandas原生的NaN对象,可能导致分支逻辑执行错误。
  3. X轴值获取偏差:原代码获取的xval是行索引,未直接提取对应行的X轴实际数值。

解决方案

关键改动点

  • 将目标列范围统一转换为数值类型,强制将非数值值转为NaN
  • 用Pandas原生的pd.isna()判断空值,避免字符串匹配误差
  • 优化最大值对应X轴值的获取逻辑,直接提取目标行的X轴数值

修改后的完整代码

import pandas as pd
import glob

# 假设X轴数据在第0列(可根据实际CSV结构调整)
X_AXIS_COL = 0

for filename in glob.glob('C:/Users/dshar/Documents/Heating Trials OF/*.csv'):
    df = pd.read_csv(filename)
    
    # 提取目标列范围并转换为数值类型,非数值转为NaN
    df1 = df.iloc[:, 100:175].apply(pd.to_numeric, errors='coerce')
    df2 = df.iloc[:, 175:250].apply(pd.to_numeric, errors='coerce')
    df3 = df.iloc[:, 250:350].apply(pd.to_numeric, errors='coerce')
    df4 = df.iloc[:, 350:420].apply(pd.to_numeric, errors='coerce')
    
    # 计算各区域最大值
    max1 = df1.max().max()
    max2 = df2.max().max()
    max3 = df3.max().max()
    max4 = df4.max().max()
    
    taree = df.loc[0, df.columns[1]]
    print(taree)
    
    # 封装获取最大值对应X轴值的函数
    def get_x_value(df_slice):
        row_idx = df_slice.idxmax(axis=1).idxmax()
        return df.iloc[row_idx, X_AXIS_COL]
    
    if pd.isna(taree):
        xval1 = get_x_value(df1)
        xval2 = get_x_value(df2)
        xval3 = get_x_value(df3)
        xval4 = get_x_value(df4)
    else:
        # 按原else分支逻辑提取X轴值
        col_idx = df1.idxmax().idxmax()
        row_idx = df1[col_idx].idxmax()
        xval1 = df.iloc[row_idx, X_AXIS_COL]
        
        col_idx = df2.idxmax().idxmax()
        row_idx = df2[col_idx].idxmax()
        xval2 = df.iloc[row_idx, X_AXIS_COL]
        
        col_idx = df3.idxmax().idxmax()
        row_idx = df3[col_idx].idxmax()
        xval3 = df.iloc[row_idx, X_AXIS_COL]
        
        col_idx = df4.idxmax().idxmax()
        row_idx = df4[col_idx].idxmax()
        xval4 = df.iloc[row_idx, X_AXIS_COL]
    
    valtype = df.loc[2, df.columns[2]]
    results = (f"{filename}: measurement={valtype}; "
               f"max1={max1} at {xval1}; "
               f"max2={max2} at {xval2}; "
               f"max3={max3} at {xval3}; "
               f"max4={max4} at {xval4}\n")
    
    print(results)
    
print('done')

补充说明

  • apply(pd.to_numeric, errors='coerce')确保所有目标列转换为数值型,无法转换的内容转为NaN,彻底避免类型错误。
  • 使用df.columns[1]代替直接索引,避免因CSV列名变化导致的索引失效问题。
  • 封装get_x_value函数减少重复代码,逻辑更易维护。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 04:36:22