如何将元组转换为整数来进行一些计算?

时间:2016-09-09 11:09:10

标签: python csv numpy matplotlib

我有41年的数据集,包括10列和l m试图用Matplotlib绘制这些数据,并且能够无误地绘制列。但是,我希望生成不同类型的图形,如年平均pcp,月平均pcp和pcp的年总和等。我从列中获取数据,并且我将这些数据转换为整数进行一些计算存在问题。

这是来自Csv文件的示例数据集:

date    day month   year    pcp1    pcp2    pcp3    pcp4    pcp5    pcp6
1.01.1979   1   1   1979    0.431   2.167   9.375   0.431   2.167   9.375
2.01.1979   2   1   1979    1.216   2.583   9.162   1.216   2.583   9.162
3.01.1979   3   1   1979    4.041   9.373   23.169  4.041   9.373   23.169
4.01.1979   4   1   1979    1.799   3.866   8.286   1.799   3.866   8.286
5.01.1979   5   1   1979    0.003   0.051   0.342   0.003   0.051   0.342
6.01.1979   6   1   1979    2.345   3.777   7.483   2.345   3.777   7.483
7.01.1979   7   1   1979    0.017   0.031   0.173   0.017   0.031   0.173
8.01.1979   8   1   1979    5.061   5.189   43.313  5.061   5.189   43.313

这是我的代码:

import csv
import numpy as np
import matplotlib.pyplot as plt



with open('output813b.csv', 'r') as csvfile:

    # get number of columns
    for line in csvfile.readlines():
        array = line.split()
        first_item = array[0]

    num_columns = len(array)
    csvfile.seek(0)

    reader = csv.reader(csvfile, delimiter=',')
    next(reader)
    included_col1 = [1]
    included_col6=[4]
    x=[]
    y=[]


    for row in reader:

            content = list(row[i] for i in included_col1)
            content2= list(row[i] for i in included_col6)
            x.append(content)
            y.append(content2)

    klm=tuple(x[i] for i in range(1,1000) if x[i]==["1979"])
    s=0
    for i in range(1,len(klm)):
        s+=y[i] #### error (for +=: 'int' and 'list')

    print (tuple(y[5])) ###example output ('2.345',)
    print (int(y [5][0])) #### error invalid literal for int() with base 10: '2.345'

元组中的元组,我使用int(y[5][0])将元组转换为int但是我得到了一个错误。我在我的代码中放入错误消息。怎么能解决这个问题,我做一些计算。提前致谢

4 个答案:

答案 0 :(得分:1)

最简单的事情是:

int(float(y[5][0]))

相反。由于您的字符串值中包含小数,因此如果不先转换为int,您将无法直接转换为float。请记住,你会失去一些精确度:

>>> int(float('2.345'))
2

因此,如果您想在计算中使用这些值,您可能只想将元组值转换为浮点值:

float(y[5][0])

答案 1 :(得分:1)

那是因为您正在尝试将十进制数转换为int

如果您想使用确切的值,可以使用float(tuple(y[5][0])) 否则,如果要截断该值,可以使用int(float(tuple(y[5][0])))

答案 2 :(得分:1)

你有两个不同的问题:

<强> 1。 s + = y [i] #### error(对于+ =:&#39; int&#39;和&#39; list&#39;)

以下是代码的相关部分:

y=[]
for row in reader:
        content2= list(row[i] for i in included_col6)
        y.append(content2)
s=0
for i in range(1,len(klm)):
    s+=y[i] #### error (for +=: 'int' and 'list')

然后:

  1. sint
  2. ycontent2
  3. 的列表
  4. content2list
  5. 然后您添加到int slist y[i]。 那是不可能的。你真的想要什么?

    <强> 2。 ####错误int()的基数为10的无效文字:&#39; 2.345&#39;

    您正在尝试将十进制数转换为int。

    您应该使用float(tuple(y[5][0]))保留浮点数,或将其转换为带有int(float(tuple(y[5][0])))

    的整数

答案 3 :(得分:1)

由于2.345不是整数,因此您需要确定如何处理浮动部分。你想把它放在地板上还是把它弄圆呢?

  • int(round(float("2.345")))提供2

  • int(math.ceil(float("2.345")))提供3

  • int(math.floor(float("2.345")))提供2