Python数组中的字符串和数字,希望将行中的所有数值求和,并将值追加到末尾

2024-09-30 06:13:09 发布

您现在位置:Python中文网/ 问答频道 /正文

初学者。我昨天刚开始尝试学习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”错误。我知道这是因为第一列中的字符串;我只是不知道该怎么做。谢谢!在


Tags: columnscsv项目字符串importnumpy数组例子
2条回答

既然你说你是初学者,我想问你是否有明确的理由使用numpy。您在这个特定范围内所做的并不是真正需要它,因此您可能更容易利用Python内置的csv处理:

import csv

output_rows = []

# Open the input file with Python's built-in open()
with open('file.csv', 'r') as csvfile:
    # Create a Reader object pointing to the csv file
    reader = csv.reader(csvfile, delimiter=',')
    # Use the Reader to loop through each row in the csv
    for row in reader:
        sum = 0
        # Each row is given to us a list; loop through that list
        # to gather up all the numbers and sum them
        # Note the [1:] says "start at position 1 (the second element)
        # and continue to the end of the list"
        for number in row[1:]:
            sum += float(number)
        # We'll give output_rows a new row that's the original
        # row + the computed sum at the end
        output_rows.append(row + [sum])

# Open the output file, passing 'w' to note it's in write mode
with open('output.csv', 'w') as outputfile:
     # Make a csv Writer object with the file
     writer = csv.writer(outputfile, delimited=',')
     for row in output_rows:
         # Write each row to the file using writerow(), which takes
         # a list and prints it to the file, using the specified delimiter
         # to separate each entry
         writer.writerow(row)

我会使用pandas.read_csv

import  pandas as pd

df = pd.read_csv("test.csv")

df["tot"] = df.sum(axis=1)
print(df)

输入:

^{pr2}$

输出:

 name  v1  v2  v3  tot
0  Bob  10  15  20   45
1  Jim  20  23  32   75
2  Sue   3  21   9   33

要将数据保存到csv,您只需要使用to_csv使用header=False如果您不想要一个头,并且使用index=False来输出不带行名/索引:

df.to_csv("test2.csv", index=False,header=False)

输出:

Bob,10,15,25
Jim,20,23,43
Sue,3,21,24

您可以指定与usecols一起使用的列,方法相同,使用axis=1将对行求和,并且将忽略任何非数字cols数据。在

相关问题 更多 >

    热门问题