我用的是Python3.9 3.9和熊猫。
我正在尝试构建一个DataFrame,但是在执行过程中我得到了以下错误:
raise ValueError(err) from err
ValueError: 13 columns passed, passed data had 14 columns
import pandas as pd
from pandas.core.frame import DataFrame
当我这么做时:
df_printers = pd.DataFrame(printers, columns=[
'id_printer',
'serial_number',
'product_number',
'installation_date',
'product_full_name',
'country_code',
'customer_name',
'sold_to_customer_name'
'warranty_ship_to_country_code',
'warranty_active',
'warranty_start_date',
'warranty_end_date',
'number_active_contracts',
'number_active_care_packs',
])
我正在尝试构建DataFrame,对象“打印机”是一个打印机列表,其中列表中的元素有14个字段,我传递的“列”也有14个字段。
但是在执行代码时,我会得到错误。
打印机是这样:
printers = []
printers.append([
str(serial_number) + "@" + str(product_number),
serial_number,
product_number,
installation_date,
product_full_name,
country_code,
customer_name,
sold_to_customer_name,
warranty_ship_to_country_code,
warranty_active,
warranty_start_date,
warranty_end_date,
number_active_contracts,
number_active_care_packs
])
如您所见,它有14列/字段。
我真的不明白这个错误,在这两种情况下,列/字段的数目都是14。
但是它告诉我,我正在传递14的元素,而不是定义一个包含13列的DataFrame。
我在Windows和Python3.9中使用了一个虚拟环境。
用PyCharm检查变量:打印机是一个包含5个元素的列表。
让我们检查一下列表中的一个元素。它必须有14列。
是!它有14列/字段,就像DataFrame所要求的那样!
那我为什么会犯这个错误呢?
在对这个问题提出负面反馈之前,请给我一些如何改进的建议。非常感谢大家。
发布于 2022-02-25 17:51:20
列列表中缺少一个后缀逗号。
columns = [
'id_printer',
'serial_number',
'product_number',
'installation_date',
'product_full_name',
'country_code',
'customer_name',
'sold_to_customer_name'
'warranty_ship_to_country_code',
'warranty_active',
'warranty_start_date',
'warranty_end_date',
'number_active_contracts',
'number_active_care_packs',
]
print(columns)
['id_printer',
'serial_number',
'product_number',
'installation_date',
'product_full_name',
'country_code',
'customer_name',
'sold_to_customer_namewarranty_ship_to_country_code',
'warranty_active',
'warranty_start_date',
'warranty_end_date',
'number_active_contracts',
'number_active_care_packs']
发布于 2022-02-25 17:35:46
如果我正确理解,我认为您的问题是在列表中添加一个列表,因此创建一个长度为1的列表,即使嵌套列表中有14个元素。
有几种方法可以解决这个问题。您可以按列表索引(即printer[0]
)进入列表项,并访问您想要的数据。
处理它的另一种方法是在附加时使用列表理解来解压列表。就像这样:
_ = [printers.append(thing) for thing in someList]
或
printers = [thing for thing in someList]
您还可以考虑创建一个单独的list变量,而不是在append方法中执行所有操作。
https://stackoverflow.com/questions/71269456
复制相似问题