【问题标题】:Values: too many values to unpack (expected 18)值:要解压的值太多(预计 18 个)
【发布时间】:2019-11-28 11:02:49
【问题描述】:

我试图用代码完成三件事,但我一直卡在第一步:

  1. 清除 csv 文件中每一列的列表。专门针对indicatorgeocodegeoareatimeperiodvalue。在这里,我不断得到太多的值来解包错误。有 18 列。我尝试将tryexcept 包括在内,但是当有更多行时,我的列表被限制为384 行。您对解决方法有什么想法吗?

  2. 为每一行创建列表

  3. 筛选和选择最近一年的 2015 年列表

这是我一直在使用的数据:https://github.com/guillermocubells/sdg9b1_642

innovation_9b1 = open('Indicators_9_6.csv','r' , encoding = 'utf-8' , errors= 'ignore') 

innovation_9b1.readline()
indicator= []
geocode = []
geoarea = []
timeperiod= []
value = []  
for lines in innovation_9b1:
    _,_,i,_,_,g,a,tp,v,_,_,_,_,_,_,_,_,_,= lines.strip().split(',')
    indicator.append(i)
    geocode.append(g)
    geoarea.append(a)
    timeperiod.append(tp)
    print(lines)

【问题讨论】:

  • 删除_,_,i,_,_,g,a,tp,v,_,_,_,_,_,_,_,_,_,中的最后一个逗号
  • 看起来很适合 pandascsv.reader()
  • Indicators_9_6.csv的编码好像是iso-8859-1,而不是utf-8

标签: python python-3.x unpack


【解决方案1】:

考虑到你正在使用的变量,你最好像这样:

for lines in innovation_9b1:
    elements = lines.strip().split(',')
    indicator.append(elements[2])
    geocode.append(elements[5])
    geoarea.append(elements[6])
    timeperiod.append(elements[7])
    print(lines)

【讨论】:

    【解决方案2】:

    您也可以使用Python's csv module,而不是手动解析 CSV,它允许您将 CSV 解析为列表或字典。

    例如,由于您的数据有标题,您可以使用csv.DictReader 将其解析为您可以通过标题寻址的字典。在此示例中,csv.Sniffer 用于确定您使用的 CSV 格式 - 我不确定它是什么。

    import csv
    
    indicator = []
    geocode = []
    geoarea = []
    timeperiod = []
    value = []  
    with open('Indicators_9_6.csv', 'r', encoding='utf-8', errors='ignore') as innovation_9b1:
        dialect = csv.Sniffer().sniff(innovation_9b1.read())
        dialect.skipinitialspace = True
        innovation_9b1.seek(0)
        reader = csv.DictReader(innovation_9b1, dialect=dialect)
        for row in reader:
            indicator.append(row["Indicator"])
            geocode.append(row["GeoAreaCode"])
            geoarea.append(row["GeoAreaName"])
            timeperiod.append(row["TimePeriod"])
            print(row)
    
    

    【讨论】:

      【解决方案3】:

      正如我在我的一个 cmets 中所说,pandas 是一个很好的例子:

      import pandas as pd
      from pathlib import Path
      
      csv_file = Path('Indicators_9_6.csv')
      
      delete_columns = [
          'Goal',
          'Target',
          'SeriesCode',
          'SeriesDescription',
          'Value',
          'Time_Detail',
          'UpperBound',
          'LowerBound',
          'BasePeriod',
          'Source',
          'FootNote',
          'Nature',
          'Units',
          '[Reporting Type]'
      ]
      
      df = pd.DataFrame(
          pd.read_csv(
              csv_file,
              encoding='iso-8859-1',
              skipinitialspace=True
          )
      )
      df.drop(delete_columns, axis=1, inplace=True)
      

      或者,您可以只阅读您想要的列:

      import pandas as pd
      from pathlib import Path
      
      csv_file = Path('Indicators_9_6.csv')
      
      columns = [
          'Indicator',
          'GeoAreaCode',
          'GeoAreaName',
          'TimePeriod'
      ]
      
      df = pd.DataFrame(
          pd.read_csv(
              csv_file,
              encoding='iso-8859-1',
              skipinitialspace=True,
              usecols=columns
          )
      )
      

      之后,很容易通过名称来引用任何列:

      >>> df.Indicator
      0       6.4.2
      1       6.4.2
      2       6.4.2
      3       6.4.2
      4       6.4.2
              ...  
      3529    9.b.1
      3530    9.b.1
      3531    9.b.1
      3532    9.b.1
      3533    9.b.1
      Name: Indicator, Length: 3534, dtype: object
      >>> 
      
      

      这是一个概念证明:

      Python 3.7.5 (default, Oct 17 2019, 12:16:48) 
      [GCC 9.2.1 20190827 (Red Hat 9.2.1-1)] on linux
      Type "help", "copyright", "credits" or "license" for more information.
      >>> import pandas as pd
      >>> from pathlib import Path
      >>> 
      >>> csv_file = Path('Indicators_9_6.csv')
      >>> 
      >>> columns = [
      ...     'Indicator',
      ...     'GeoAreaCode',
      ...     'GeoAreaName',
      ...     'TimePeriod'
      ... ]
      >>> 
      >>> df = pd.DataFrame(
      ...     pd.read_csv(
      ...         csv_file,
      ...         encoding='iso-8859-1',
      ...         skipinitialspace=True,
      ...         usecols=columns
      ...     )
      ... )
      >>> df
           Indicator  GeoAreaCode  GeoAreaName  TimePeriod
      0        6.4.2            4  Afghanistan        2000
      1        6.4.2            4  Afghanistan        2005
      2        6.4.2            4  Afghanistan        2010
      3        6.4.2            4  Afghanistan        2015
      4        6.4.2            8      Albania        2000
      ...        ...          ...          ...         ...
      3529     9.b.1          894       Zambia        2012
      3530     9.b.1          894       Zambia        2013
      3531     9.b.1          894       Zambia        2014
      3532     9.b.1          894       Zambia        2015
      3533     9.b.1          894       Zambia        2016
      
      [3534 rows x 4 columns]
      >>> 
      

      希望对你有帮助。

      【讨论】:

      • 谢谢!出于这个项目的目的,我们仅限于我们创建的内容,因此不能真正使用 pandas。但会记住进一步的任务
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-13
      • 2016-12-08
      • 2019-12-28
      • 2021-10-20
      • 1970-01-01
      • 2012-09-27
      相关资源
      最近更新 更多