0

因此,我编写了小测试代码来计算文件夹中所有 csv 文件的平均值。

parser = argparse.ArgumentParser(description='avg data from csv to csv')
parser.add_argument('--input', required = True)
parser.add_argument('--output', required = True)
args = parser.parse_args()

# Get command arguments
input_files_path = args.input
output = args.output

avg = []
for infile in glob.glob(input_files_path+"*.csv"):
        a = np.loadtxt(infile, delimiter=",")
        mean = np.mean(a, axis=0)
        avg.append((mean))
        print infile
np.savetxt(output,(avg), fmt = "%.1f", delimiter=", ")

但是现在的问题是,当我尝试将文件名也保存在 csv 文件中时,如下所示:

parser = argparse.ArgumentParser(description='avg data from csv to csv')
parser.add_argument('--input', required = True)
parser.add_argument('--output', required = True)
args = parser.parse_args()

# Get command arguments
input_files_path = args.input
output = args.output

avg = []
for infile in glob.glob(input_files_path+"*.csv"):
        a = np.loadtxt(infile, delimiter=",")
        mean = np.mean(a, axis=0)
        avg.append((infile,(mean)))
        print infile
np.savetxt(output,(avg), fmt = "%.1f", delimiter=", ")

它抛出一个错误:

    np.savetxt(output,(avg), fmt = "%.1f", delimiter=", ")
  File "/usr/lib/python2.7/dist-packages/numpy/lib/npyio.py", line 963, in savetxt
    X = np.asarray(X)
  File "/usr/lib/python2.7/dist-packages/numpy/core/numeric.py", line 235, in asarray
    return array(a, dtype, copy=False, order=order)
ValueError: cannot set an array element with a sequence

我似乎不明白问题是什么。也许是因为我试图将一个字符串附加到一个浮点数?我检查了fmtnumpy 中的 s .. 但我没有发现任何有趣的东西。

/usr/lib/python2.7/dist-packages/numpy/lib/npyio.py:773: UserWarning: loadtxt: Empty input file: "../robalo-31.1/op.csv"
  warnings.warn('loadtxt: Empty input file: "%s"' % fname)
/usr/lib/python2.7/dist-packages/numpy/core/fromnumeric.py:2374: RuntimeWarning: invalid value encountered in double_scalars
  return mean(axis, dtype, out)
4

1 回答 1

1

我猜你提供的格式字符有问题np.savetxt。(你有一个字符串浮点元组,你是分隔符意味着你只使用浮点数)。我建议csv这样做:

>>> import csv
>>> import StringIO
>>> g = StringIO.StringIO()
>>> writer = csv.writer(g,delimiter=',')  #this is the part that is applicable
>>> writer.writerows(lst)
>>> g.seek(0)
>>> print g.read()
foo,2
bar,4

所以我猜你的代码可能很简单:

with open(output,'wb') as fout:
    writer = csv.writer(fout,delimiter=',') 
    writer.writerows(avg)

代替

np.savetxt(output,(avg), fmt = "%.1f", delimiter=", ")
于 2013-01-31T21:28:22.637 回答