Python pandas 数据帧读取from_records,“AssertionError:1列传递,传递数据有22列” [英] Python pandas dataframe read from_records, "AssertionError: 1 columns passed, passed data had 22 columns"
问题描述
我有一个列表,其中 a
的长度为 806
。我想导入到数据框,列表中的第一个项目是列名。我的代码是:
I have a list where a
is 806
in length. I want to import to a dataframe where the first item in the list is the column name. My code is:
import pandas as pd
b = pd.DataFrame.from_records(a[1:],columns=[a[0]])
这给我一个错误 AssertionError :1列通过,传递数据有22列
,而显然我只有一列。
this gives me an error of AssertionError: 1 columns passed, passed data had 22 columns
while clearly i have only one column.
我已经尝试了代码的表示,有用。所以我不知道这里发生了什么。这是代码的代码:
I've tried a representation of the code and it works. So I'm not sure what is going on here. Here is a representation of the code:
import pandas as pd
arr= ['title', 'a','b','','','']
arr= filter(None, arr)
b = pd.DataFrame.from_records(arr[1:],columns=[arr[0]] )
我的列表必须出错?我打印出 a
,它看起来很好,像一个常规列表。我已经粘贴了 a
的打印输出,并将其作为变量列表
,并给出了相同的错误 AssertionError:传递1列,传递数据有22列
。看起来像我的名单有问题。还有什么可以调试?
Must be something wrong with my list? I printed out a
and it looks fine, like a regular list. I have pasted the printed output of a
and placed that as the variable list
, and it gives me the same error AssertionError: 1 columns passed, passed data had 22 columns
. Seems like something wrong with my list. What else can I do to debug?
编辑(根据DSM建议):
Edit (based on DSM suggestion):
import pandas as pd
arr=['Title', '000660.ks']
b = pd.DataFrame.from_records(arr[1:],columns=[arr[0]] )
这给了 AssertionError:1列传递,传递数据有8列
推荐答案
而不是使用 from_records
想要使用默认的DataFrame构造函数。
Instead of using from_records
you want to use the default DataFrame constructor.
from_records
期望一些可重复的东西的列表,例如,字符串'0006660正在以
('0','0',...,'')的形式读入.ks'
在数据中收到有关8列的错误。
from_records
expects a list of something iterable, so for example, the string '0006660.ks'
is being read in as ('0','0',... ,'s')
which is why you are getting an error about 8 columns in the data.
b = pd.DataFrame(a[1:], columns=[a[0]])
这篇关于Python pandas 数据帧读取from_records,“AssertionError:1列传递,传递数据有22列”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!