You need to enable JavaScript to run this app. pandas的df.sub方法在argparse传参时结果全为NaN的异常问题
优惠活动
大模型
产品
解决方案
定价
更多

pandas的df.sub方法在argparse传参时结果全为NaN的异常问题

问题概述

使用pandas DataFrame.sub()实现按参考列的行级归一化时,出现不同运行环境下的行为不一致异常:

  • 在Jupyter Notebook中硬编码传入参考列名时,计算结果完全符合预期
  • 改写为支持argparse传参的独立终端脚本后,除参考列外其余列全部返回NaN
    当前运行环境为Python 3.6.7、Pandas 1.1.2。
复现代码与对应结果

正常运行的基础版本

基础测试代码:

import pandas as pd
def normalize(df,col):
    '''Enter the column value in "col".'''
    return df.sub(df[col], axis=0)
df = pd.read_csv('norm_debug.txt', sep='\t', index_col=0)
print(df.head(3))
new = normalize(df,'A')
print(new.head(3))

对应正常输出:

df:
             A  B   C   D  E
target_id                    
one        10.0  3  20  10  1
two        10.0  4  30  10  1
three       6.7  5  40  10  1

             A    B     C    D    E
target_id                          
one        0.0 -7.0  10.0  0.0 -9.0
two        0.0 -6.0  20.0  0.0 -9.0
three      0.0 -1.7  33.3  3.3 -5.7

异常的argparse脚本版本

可执行脚本代码:

import argparse
import platform
import os
import pandas as pd

def normalize(df,col):
    '''Normalize the log table with desired column, 
    Enter the column value in "col".'''
    return df.sub(df[col], axis=0)

parser = argparse.ArgumentParser(description='''Manipulate tables ''',
    usage='python3 %(prog)s -e input.tsv [-nm col_name] -op output.tsv',
    epilog='''Short prog. desc:\
    Pass the expression matrix to filter, log2(val) etc.,''')

parser.add_argument("-e","--expr", metavar='', required=True, help="tab-delimited expression matrix file")
parser.add_argument("-op","--outprefix", metavar='', required=True, help="output file prefix")
parser.add_argument("-nm","--norm", metavar='', required=True, nargs=1, type=str, help="Normalize table based on column chosen")

args=parser.parse_args()
print(args)
if (os.path.isfile(args.expr)):
    df = pd.read_csv(args.expr, sep='\t', index_col=0)
    print(df.head(3))
    if(args.norm):
        norm_df = normalize(df,args.norm)
        print(norm_df.head(3))
        outfile = args.outprefix + ".normalized.tsv"
        norm_df.to_csv(outfile, sep='\t')
        print("Normalized table written to ", outfile)
    else:
        print("Provide valid option...")
else:
    print("Please provide proper input..")

终端运行命令:

python norm_debug.py -e norm_debug.txt -nm A -op norm_debug

对应异常输出:

A  B   C   D  E
target_id                    
one        10.0  3  20  10  1
two        10.0  4  30  10  1
three       6.7  5  40  10  1

             A   B   C   D   E
target_id                     
one        0.0 NaN NaN NaN NaN
two        0.0 NaN NaN NaN NaN
three      0.0 NaN NaN NaN NaN
根本原因

问题完全出在argparse的参数配置上,和pandas计算逻辑、运行环境无关:

  • 定义-nm/--norm参数时加了nargs=1配置,这个参数会让解析后的args.norm不是纯字符串值,而是单元素列表,也就是传入normalize函数的col值不是字符串'A',而是列表['A']
  • 当用df[col]取列时,如果传入的是字符串'A',pandas会返回一个和行索引对齐的一维Series,配合df.sub(series, axis=0)可以正常做逐行减法
  • 当传入的是列表['A']时,pandas会把这个参数识别为多列选取规则,返回一个只有A列的二维单列DataFrame。用这个二维DataFrame做减法时,pandas会自动按列索引对齐,和原df的B/C/D/E列名无法匹配,因此除了同名列A的计算结果保留外,其余列全部返回NaN。
修复方案
  • 方案1:移除--norm参数定义里的nargs=1配置,这时候argparse会直接返回纯字符串值,和硬编码传参的逻辑完全一致
  • 方案2:保留原参数配置,调用normalize函数时取列表的第一个元素,也就是把normalize(df,args.norm)改为normalize(df, args.norm[0])
  • 快速验证方式:在normalize函数开头打印type(col)和col的值,就能直接看到传入的参数类型差异。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.18 13:06:06