【问题标题】:Python Pandas ValueError Arrays Must be All Same LengthPython Pandas ValueError 数组的长度必须相同
【发布时间】:2016-11-05 18:57:36
【问题描述】:

遍历大量 .mp3 链接以获取元数据标签并将其保存到 Excel 文件中。导致此错误。我很感激任何帮助。谢谢。

    #print is_connected();

    # Create a Pandas dataframe from the data.
df = pd.DataFrame({'Links' : lines ,'Titles' : titles , 'Singers': finalsingers , 'Albums':finalalbums , 'Years' : years})


    # Create a Pandas Excel writer using XlsxWriter as the engine.
writer = pd.ExcelWriter(xlspath, engine='xlsxwriter')

    # Convert the dataframe to an XlsxWriter Excel object.
df.to_excel(writer, sheet_name='Sheet1')
    #df.to_excel(writer, sheet_name='Sheet1')


    # Close the Pandas Excel writer and output the Excel file.
writer.save()

Traceback (most recent call last):
  File "mp.py", line 87, in <module>
    df = pd.DataFrame({'Links' : lines ,'Titles' : titles , 'Singers': finalsingers , 'Albums':finalalbums , 'Years' : years})
  File "C:\Python27\lib\site-packages\pandas\core\frame.py", line 266, in __init__
    mgr = self._init_dict(data, index, columns, dtype=dtype)
  File "C:\Python27\lib\site-packages\pandas\core\frame.py", line 402, in _init_dict
    return _arrays_to_mgr(arrays, data_names, index, columns, dtype=dtype)
  File "C:\Python27\lib\site-packages\pandas\core\frame.py", line 5409, in _arrays_to_mgr
    index = extract_index(arrays)
  File "C:\Python27\lib\site-packages\pandas\core\frame.py", line 5457, in extract_index
    raise ValueError('arrays must all be same length')
ValueError: arrays must all be same length

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    您可以这样做来避免该错误

    a = {'Links' : lines ,'Titles' : titles , 'Singers': finalsingers , 'Albums':finalalbums , 'Years' : years}
    df = pd.DataFrame.from_dict(a, orient='index')
    df = df.transpose()
    

    说明:

    这将创建 DataFrame,因为每个键(例如 'Links')是一行,并且像这样缺失的值实际上是缺失的列,这对 pandas 没有问题(只有缺失的行导致 ValueError 在创建过程中)之后你转置 DataFrame(翻转轴)并将行变为列,从而得到您最初想要的 DataFrame。

    【讨论】:

    • 它对我不起作用。它将索引添加为第一行,并显然随机拆分行
    • 从另一个问题尝试这个答案,这对我有用:stackoverflow.com/a/45052003/4682460
    • 这到底是做什么的?
    • 我也很好奇这到底是如何工作的。同时,我很高兴它确实有效。 a 中的值比 a 中的最长列表短,并用 None 填充,这是在这种情况下所期望的。
    • @Richard 这在创建 DataFrame 时起作用,因为每个键(例如“链接”)是一行,这样缺失的值实际上是缺失的列,这对于熊猫来说没有问题(只有缺失的行是在创建期间),然后您转置数据框(翻转轴)并将行变为列,这会产生您最初想要的数据框。这有帮助吗?
    【解决方案2】:

    它告诉您数组(行、标题、finalsingers 等)的长度不同。您可以通过

    进行测试
    print(len(lines), len(titles), len(finalsingers)) # Print all of them out here
    

    这将向您显示哪些数据格式不正确,然后您需要进行一些调查以找出纠正此问题的正确方法。

    【讨论】:

      【解决方案3】:

      你可以用空元素填充最短的列表:

      def pad_dict_list(dict_list, padel):
          lmax = 0
          for lname in dict_list.keys():
              lmax = max(lmax, len(dict_list[lname]))
          for lname in dict_list.keys():
              ll = len(dict_list[lname])
              if  ll < lmax:
                  dict_list[lname] += [padel] * (lmax - ll)
          return dict_list
      

      【讨论】:

      • padel 是什么?
      • @loretoparisi 这是您想用作填充字典值的元素
      【解决方案4】:

      重复的变量名给我造成了这个问题

      【讨论】:

      • 谢谢,也是我的问题
      【解决方案5】:

      我在将 JSON 文件读取到 pandas 框架时遇到了同样的错误。添加linesbool,默认False参数解决了这个问题。

      StringData = StringIO(obj.get()['Body'].read().decode('utf-8'))
                      mydata = pdf.read_json(StringData, lines=True)
      

      【讨论】:

        猜你喜欢
        • 2021-12-07
        • 1970-01-01
        • 2018-11-04
        • 2017-12-16
        • 1970-01-01
        • 1970-01-01
        • 2022-11-29
        • 2019-02-24
        相关资源
        最近更新 更多