繁体   English   中英

如何使用 csv 文件在 Python 中对数据求和

[英]How to sum data at Python with csv file

例如,我有如下的 csv 文件。

    apple orange tomato
0     4      5     2  
1     5      6     4
2     1      3     5
3     2      2     6

而且,总而言之,我想创建一个新列作为每个水果的总和。

    apple orange tomato  total
0     4      5     2      11
1     5      6     4      15
2     1      3     5      9
3     2      2     6      10

它应该只通过“for”命令来制作,还是有更聪明的方式像 lambda? 你能推荐一些好的方法吗? 非常感谢。

将您的数据返回到list然后使用sum

>>>a = [1,2,3]
>>>sum(a)
6

或者使用numpy.sum() 在这里阅读更多

>>>import numpy as np
>>>np_array_2x3 = np.array([[0,2,4],[1,3,5]])
>>>np_array_2x3
array([[0, 2, 4],
       [1, 3, 5]])
>>>np.sum(np_array_2x3, axis = 1)
array([6, 9])

如果它是一个大的 csv 文件,你可以尝试使用 Pandas,它会让你的代码看起来更干净:

# This will also read in your index column, you might
# have to deal with that in some other way

import pandas as pd
df = pd.read_csv("file.csv")
df['sum'] = df.sum(axis = 0).reset_index(drop = True)
df.to_csv("new_file.csv")

# Documentation for DataFrame.sum() is at https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.sum.html

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM