Python Pandas ValueError数组必须全部相同

时间:2016-11-05 18:57:37

标签: python pandas

迭代一大堆.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 个答案:

答案 0 :(得分:20)

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

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

答案 1 :(得分:5)

它告诉你数组(行,标题,终结者等)的长度不一样。您可以通过

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

这将显示哪些数据格式不正确,然后您需要调查一下纠正这种情况的正确方法。

答案 2 :(得分:1)

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

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

答案 3 :(得分:0)

重复的变量名对我造成了此问题

答案 4 :(得分:0)

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

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