初学者。我昨天刚开始尝试学习Python,作为一个暑期项目。在
我有一个CSV存储为一个数组。它比这个例子稍微大一点,但是如果你能告诉我如何在这个例子上做,我可能可以推断它。在
Bob | 10 | 15 | 20
Jim | 20 | 23 | 32
Sue | 03 | 21 | 09
我想在表的末尾添加一个列来计算值的总和,显然忽略了第一列中的字符串。所以要得到这样的结果:
^{pr2}$到目前为止,我有这样的代码
import numpy
import csv
vlhpcsv = open('file.csv')
importeddata = csv.reader(vlhpcsv)
from numpy import genfromtxt
genfromtxt_vlhp = genfromtxt('file.csv',delimiter=',', skip_header=1, dtype=None, usecols=(9,10,11,19,21,22))
relevant_columns = numpy.array(genfromtxt_vlhp)
print(relevant_columns)
这符合我的预期,并向我展示了原始CSV的精简版本,其中只包含我关心的数据。但是,任何试图在之后求和和和追加的尝试都会遇到一个“cannotperformerereducewithflexibletype”错误。我知道这是因为第一列中的字符串;我只是不知道该怎么做。谢谢!在
既然你说你是初学者,我想问你是否有明确的理由使用numpy。您在这个特定范围内所做的并不是真正需要它,因此您可能更容易利用Python内置的csv处理:
我会使用pandas.read_csv:
输入:
^{pr2}$输出:
要将数据保存到csv,您只需要使用to_csv使用
header=False
如果您不想要一个头,并且使用index=False
来输出不带行名/索引:输出:
您可以指定与
usecols
一起使用的列,方法相同,使用axis=1
将对行求和,并且将忽略任何非数字cols数据。在相关问题 更多 >
编程相关推荐