用python计算csv文件中的数据总和

时间:2018-10-17 07:09:45

标签: python pandas csv

现在,我正在尝试从csv文件计算值的总和,并且这些值在特定列中。例如,在下面的代码中,第11列中的数据是必需的,我非常珍惜您的所有建议。这是我的代码:

import pandas as pd
new_rows = []
df = pd.read_csv('02052018.csv')
x = df.iloc[:,6]
for row in x:
    row = [float(val) for val in row]
    row.append(sum(row))
    new_rows.append(row)

这是错误:

File "C:/Users/AK6PRAKT/Desktop/Daten.sammeln.Aufgabe/neletxt.py", line 15, in <module>
row = [float(val) for val in row]
TypeError: 'float' object is not iterable

我不知道该代码出了什么问题。

顺便说一句,这是csv文件中数据的格式。

2016/05/02 10:47:45,14.1,20.1,N.C.,170.7,518.3,-1259,-12.61,375.8,44.92,13.76,92.74,132.6,38.86,165.3,170.9,311.5,252.3,501.2,447.2,378.4,35.48,7.868,181.2, 2119,
2016/05/02 10:49:47,14.1,21.3,N.C.,74.34,273.5,-651.2,603.5,91.96,14.57,-21.17,89.67,123.7,32.22,150.6,202.2,296.0,297.7,509.9,409.2,353.1,36.49,20.25,635.6, 2119,
2016/05/02 10:51:48,14.1,21.9,N.C.,105.4,437.5,-349.4,-256.3,395.4,65.94,-3.818,85.26,143.8,33.52,-0.415,310.2,1.242,0.910,6.207,20.73,34.01,35.14,-12.38,526.9, 
2016/05/02 11:47:59,14.0,17.2,N.C.,1.609,0.760,0.993,-137.9,0.980,0.871,1.204,0.864,0.991,0.997,  NAN,119.4,1.037,1.782,0.588,0.893,0.043,-18.57,-7.459,3.864, 2114,

1 个答案:

答案 0 :(得分:3)

执行此操作时:

x = df.iloc[:,6]

您只能从nr 6列中获得带有浮点数的Series对象。由于熊猫猜测它是浮点数,因此该对象仅包含floats。

因此,当您执行此操作时:

for row in x:

“行”不是文件中的一行,它是x列中的值。该float值不能插入

   [ .... for val in row  ]

如果您想要nr 6列的总和,就可以

my_sum =  df.iloc[:,6].sum()