Pandas ValueError 数组长度必须相同

66
遍历一个包含大量 .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
5个回答

147

你可以这样做来避免那个错误

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。


1
它对我不起作用。它将索引添加为第一行,并似乎随机拆分行。 - robertspierre
1
尝试使用这个来自不同问题的答案,对我有效:https://dev59.com/nKPia4cB1Zd3GeqPxFqQ#45052003 - lobi
17
这到底是做什么的? - Richard
我也很好奇这是如何工作的。与此同时,我很高兴它确实能够工作。在a中长度比最长列表短的值会被填充为None,这是我们所期望的情况。 - rodrigo-silveira
@Richard 这个方法可行,因为它将每个键(例如“Links”)作为一行创建了DataFrame。这样缺失的值实际上是缺失的列,对于pandas来说没有问题(只有在创建时缺少行)。然后你可以转置数据框(翻转轴),将行变成列,这样就得到了最初想要的数据框。这有帮助吗? - gustavz

14

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

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


dict_list = {'Links': [1, 2, 3], 'Titles': [1, 2, 3, 4], 'Singers': [1, 2], 'Albums': [1, 2, 3], 'Years': [1, 2, 3, 4]}
dict_list = pad_dict_list(dict_list, 0)
print(dict_list)

输出

{'Links': [1, 2, 3, 0], 'Titles': [1, 2, 3, 4], 'Singers': [1, 2, 0, 0], 'Albums': [1, 2, 3, 0], 'Years': [1, 2, 3, 4]}

什么是 padel - loretoparisi
2
@loretoparisi 这是您想要用作填充字典值元素的东西。 - R. Kulebyakin

14

这是告诉您数组(行、标题、最终歌手等)的长度不同。 您可以通过测试来验证:

print(len(lines), len(titles), len(finalsingers)) # Print all of them out here

这将展示给您哪些数据是格式不正确的,然后您需要进行一些调查来确定正确纠正的方法。


5
变量名的重复导致了我的问题。

3
我在读取JSON文件到pandas框架时也遇到了相同的错误。添加linesbool,默认值为False的参数解决了这个问题。
StringData = StringIO(obj.get()['Body'].read().decode('utf-8'))
                mydata = pdf.read_json(StringData, lines=True)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接