【问题标题】:How to pass argparse value into function and assign value to dataframe?如何将 argparse 值传递给函数并将值分配给数据框?
【发布时间】:2025-11-26 23:30:01
【问题描述】:

我已经为我的脚本设置了一些 argparse 参数,如下所示:

import argparse


parser = argparse.ArgumentParser()
parser.add_argument("--file", "-i", type=str, required=True)
parser.add_argument("--outfile", "-o", type=str, required=False)
parser.add_argument("--tab", "-t", type=str, required=False)
parser.add_argument("--tab_result", "-tr", type=str, required=False)
args = parser.parse_args()


#assign value too variables
infile = args.file
outfilepath = args.outfile
tabs = args.tab
tab_result = args.tab_result

我需要将上面每个 argparsers 的变量传递给一个函数并将值分配给一个数据框。我正在尝试这样做:

def func1():
    print(infile)
    doc = pd.DataFrame()
    doc['file'] =  infile
    doc['output_table_name'] = outfilepath
    doc['output_table_fields'] = json_normalized['index'] #from another df, works fine
    doc['output_table_datatypes'] = json_normalized['dtypes.name'] #from another df, works fine
    writer = pd.ExcelWriter(tabs)
    doc.to_excel(writer,args.documentor_tab)
    writer.save()
    #print(infile)
    #print(outfilename)
    print(doc)

    return doc


print('wrote document')

func1()

当我打印此数据框时,infileoutpathfile argparse 值不会分配给数据框列,但是所有其余的 argparse 值都会分配。

我做错了什么,并非所有来自 argparse 的值都被分配给数据框?

【问题讨论】:

    标签: python-3.x pandas arguments argparse


    【解决方案1】:

    doc['file'] 引用了 'file' 列,因此您不能在数据框中有任何行之前将其设置为字符串。

    如果json_normalized 中只有一行,那么您可能想要这样的内容:

    def func1(infile, outfilepath, tabs, tabs_result, json_normalized):
        doc = pd.DataFrame(columns=['file', 'output_table_name', 'output_table_fields', 'output_table_datatypes'])
    
        index = json_normalized['index'][0]
        dtypes_name = json_normalized['dtypes.name'][0]
        doc.loc[0] = [infile, outfilepath, index, dtypes_name]
    
        ...
    
        return doc
    

    或者如果你的意思是写一整列index,那么交换顺序:

    def func1(infile, outfilepath, tabs, tabs_result, json_normalized):
        doc = pd.DataFrame(columns=['file', 'output_table_name', 'output_table_fields', 'output_table_datatypes'])
        doc['output_table_fields'] = json_normalized['index']
        doc['output_table_datatypes'] = json_normalized['dtypes.name']
        doc['output_table_name'] = outfilepath
        doc['file'] =  infile
    
        ...
    
        return doc
    

    【讨论】:

      【解决方案2】:

      argparse 和在函数中传递/使用变量不是问题。问题在于如何创建数据框。

      考虑这个精简的例子:

      In [255]: doc = pd.DataFrame()                                                  
      In [256]: doc['file'] = 'foobar'                                                
      In [257]: doc['outfile'] = 'anothername'                                        
      In [258]: doc                                                                   
      Out[258]: 
      Empty DataFrame
      Columns: [file, outfile]
      Index: []
      In [259]: doc['col'] = [1,2,3,4]                                                
      In [260]: doc                                                                   
      Out[260]: 
        file outfile  col
      0  NaN     NaN    1
      1  NaN     NaN    2
      2  NaN     NaN    3
      3  NaN     NaN    4
      

      初始分配适用于一个空框架,没有任何行。

      在创建行后将常量值分配给列:

      In [261]: doc['file'] = 'foobar'                                                
      In [262]: doc['outfile'] = 'anothername'                                        
      In [263]: doc                                                                   
      Out[263]: 
           file      outfile  col
      0  foobar  anothername    1
      1  foobar  anothername    2
      2  foobar  anothername    3
      3  foobar  anothername    4
      

      或者,您可以在开始时指定行索引:

      In [265]: doc = pd.DataFrame(index=np.arange(5))                                
      In [266]: doc                                                                   
      Out[266]: 
      Empty DataFrame
      Columns: []
      Index: [0, 1, 2, 3, 4]
      In [267]: doc['file'] = 'foobar'                                                
      In [268]: doc['outfile'] = 'anothername'                                        
      In [269]: doc                                                                   
      Out[269]: 
           file      outfile
      0  foobar  anothername
      1  foobar  anothername
      2  foobar  anothername
      3  foobar  anothername
      4  foobar  anothername
      

      【讨论】: