【问题标题】:Command line argument in Histogram直方图中的命令行参数
【发布时间】:2017-12-12 21:35:20
【问题描述】:

我正在编写一些代码,它从目录中导入的 excel 文件制作直方图,并根据某些参数对数据进行分箱,并相应地导出新的 excel 文件,将其分箱到各自的箱中,例如。如果有一个数字 5.16,那么 bin (5,10] 的 bin 计数将增加 1,依此类推。但是,我想写一些东西,我可以在其中输入一个可以相应更改 bin 的特定值,例如我想要 3 个 bin,我会选择 n=3,现在代码会相应地 bin,这样它会生成 bin (0,3]、(3,6] 等,并且适用与以前相同的规则。原始代码是:

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import openpyxl
from pandas import ExcelWriter
import os

datadir = '/Users/user/Desktop/Newfolder/'

for file in os.listdir(datadir):
    if file.endswith('.xlsx'):
        data = pd.read_excel(os.path.join(datadir, file))
        counts, bins, patches = plt.hist(data.values, bins=range(0, 
        int(max(data.values)+5), 5))
        df = pd.DataFrame({'bin_leftedge': bins[:-1], 'count': counts})
        plt.title('Data')
        plt.xlabel('Neuron')
        plt.ylabel('# of Spikes')
        plt.show()

        outfile = os.path.join(datadir, file.replace('.xlsx', '_bins.xlsx'))
        writer = pd.ExcelWriter(outfile)
        df.to_excel(writer)
        writer.save()

我的想法是使用 argparse 作为命令行参数,我可以输入 bin 中的更改,所以我写道:

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import openpyxl
from pandas import ExcelWriter
import os
import argparse

datadir = '/Users/user/Desktop/Newfolder/'

parser = argparse.ArgumentParser(description = 'Calculating the bin width')
parser.add_argument('n', type=int, help='Changing of the width')
args = parser.parse_args()

def vary(n):
    wid = n
     return wid

if __name__ == '__main__':
    print(vary(args.n))

for file in os.listdir(datadir):
    if file.endswith('.xlsx'):
       data = pd.read_excel(os.path.join(datadir, file))
       counts, bins, patches = plt.hist(data.values, bins=range(0, 
       int(max(data.values)+vary(n)), vary(n)))
       df = pd.DataFrame({'bin_leftedge': bins[:-1], 'count': counts})
       plt.title('Data')
       plt.xlabel('Neuron')
       plt.ylabel('# of Spikes')
       plt.show()

       outfile = os.path.join(datadir, file.replace('.xlsx', '_bins.xlsx'))
       writer = pd.ExcelWriter(outfile)
       df.to_excel(writer)
       writer.save()

如果这看起来很白痴,我提前道歉,因为我对编码还很陌生,而且对任何事情都不太了解。无论如何,我得到一个错误说

Traceback (most recent call last):
File "\Users\user\Desktop\Bins.py", line 25, in <module>
        counts, bins, patches = plt.hist(data.values, bins=range(0, int(max(data.values)+vary(n)), vary(n)))
NameError: name 'n' is not defined

我能得到一些帮助吗,我将如何在直方图中实现这个命令行参数 (argparse),以便每次我需要更改它们时都可以输入相应的 bin。任何帮助将不胜感激,谢谢您

【问题讨论】:

  • 您设置了argsargs.n,但您没有在任何地方定义n
  • 通常函数定义在if __name__ 块之前,之后的所有代码都缩进。也就是说,该块定义了仅在用作脚本时才运行的代码。导入模块时可能使用的代码放置在 9 之前和该块之外。参数解析通常仅作为脚本调用的一部分完成。
  • 如果 hpauli 的回答能帮助您解决问题,请考虑接受。

标签: python excel command-line-arguments argparse


【解决方案1】:

无需过多处理代码,使用sys 模块即可轻松处理命令行参数:

import sys
print sys.argv # first element is the script name, then follow the parameters as strings

所以这个脚本,如果我将它命名为sysArgs.py并在控制台中使用一些参数调用它,就会打印出来

python sysArgs.py lala 5
['sysArgs.py', 'lala', '5']

如果你只想传递一个参数n,那就改成

import sys
n = int(sys.argv[1])
# do stuff with n other than printing it
print n

【讨论】:

    【解决方案2】:

    以下是我组织您的代码的方式。 main可以重组,但我的重点是命令行解析的位置。

    datadir = '/Users/user/Desktop/Newfolder/'
    n = 3  # a default if not used with argparse
    
    def main(datadir, n):
        # might split the load and the plot functions
        # or put the action for one file in a separate function
    
        for file in os.listdir(datadir):
            if file.endswith('.xlsx'):
               data = pd.read_excel(os.path.join(datadir, file))
               counts, bins, patches = plt.hist(data.values, bins=range(0, 
               int(max(data.values)+n), n))
               df = pd.DataFrame({'bin_leftedge': bins[:-1], 'count': counts})
               plt.title('Data')
               plt.xlabel('Neuron')
               plt.ylabel('# of Spikes')
               plt.show()
    
               outfile = os.path.join(datadir, file.replace('.xlsx', '_bins.xlsx'))
               writer = pd.ExcelWriter(outfile)
               df.to_excel(writer)
               writer.save()
    
    if __name__ == '__main__':
        # run only as a script; not on import
        # if more complicated define this parser in a function
    
        parser = argparse.ArgumentParser(description = 'Calculating the bin width')
        parser.add_argument('n', type=int, help='Changing of the width')
        args = parser.parse_args()
    
        print(args)  # to see what argparse does
        main(datadir, args.n)
        # main(args.datadir, args.n) # if parser has a datadir  argument
    

    (我没有测试过。)

    【讨论】:

    • 非常感谢兄弟,你帮了我很大的忙!
    猜你喜欢
    • 2012-01-30
    • 2012-02-25
    • 2016-03-25
    • 2012-07-06
    • 2012-10-04
    • 2020-08-17
    • 2012-04-24
    • 2011-03-23
    • 2011-03-24
    相关资源
    最近更新 更多