简体   繁体   English

如何将两个不同长度的列表合并为 Pandas 数据框?

[英]How to merge two lists of different lengths as a Pandas dataframe?

I have two lists to be merged as a pandas dataframe.我有两个列表要合并为熊猫数据框。 The columns would be the header of the CSV and the data contains the rows of data as a single list.列将是 CSV 的标题,数据包含作为单个列表的数据行。

import pandas as pd
columns = [column[0] for column in cursor.description]
len(columns)
>5

data = cursor.fetchall()
len(data)
>2458

len(data[0])
>5

df = pd.DataFrame(data=data, index=None, columns=columns)
>ValueError: Shape of passed values is (1, 2458), indices imply (5, 2458).

Can someone help me merging these two lists as a pandas dataframe?有人可以帮我将这两个列表合并为熊猫数据框吗? Please let me know if I am missing on any other details.如果我遗漏了任何其他细节,请告诉我。 Thank you!谢谢!

The presence of a cursos indicates you're using pyodbc .光标的存在表明您正在使用pyodbc data contains pyodbc.Row objects and hence the pd.DataFrame constructor fails to split the data. data包含pyodbc.Row对象,因此pd.DataFrame构造函数无法拆分数据。

Try this尝试这个

df = pandas.DataFrame([tuple(t) for t in cursor.fetchall()], columns=columns)

Your csv file apparently has 5 columns, but your data is a single list of values.您的 csv 文件显然有 5 列,但您的数据是单个值列表。 That means that you also only need 1 column header.这意味着您也只需要 1 个列标题。 Pandas complains right now because the dimension of the column list (5) does not match the number of columns in your data (1). Pandas 现在抱怨是因为列列表 (5) 的维度与数据 (1) 中的列数不匹配。 You could fix this for example by saying:例如,您可以通过以下方式解决此问题:

df = pd.DataFrame(data=data, index=None, columns=[columns[0]])

That is assuming that you want to use the first column name.那是假设您要使用第一个列名。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM