【发布时间】: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。任何帮助将不胜感激,谢谢您
【问题讨论】:
-
您设置了
args和args.n,但您没有在任何地方定义n。 -
通常函数定义在
if __name__块之前,之后的所有代码都缩进。也就是说,该块定义了仅在用作脚本时才运行的代码。导入模块时可能使用的代码放置在 9 之前和该块之外。参数解析通常仅作为脚本调用的一部分完成。 -
如果 hpauli 的回答能帮助您解决问题,请考虑接受。
标签: python excel command-line-arguments argparse