在使用 Pandas DataFrame 的 append() 方法时,可能会遇到 TypeError: Can only append a dict if ignore_index=True 错误。这个错误通常是由于直接将一个列表传递给 append() 方法导致的,而 append() 方法只能接受一个字典作为参数。

错误示例:

data_inicial = pd.DataFrame(columns=['survived', 'pclass', 'sex', 'age', 'sibsp', 'parch', 'fare', 'embarked'])

Rose_infor = [1, 1, 'female', 20, 1, 0, 100.000, 'S']

data_inicial.append({'survived': 0, 'pclass': 3, 'sex': 1, 'age': 23, 'sibsp': 1, 'parch': 0, 'fare': 5.0000, 'embarked': 2})
data_inicial.append({'survived': 1, 'pclass': 1, 'sex': 0, 'age': 20, 'sibsp': 1, 'parch': 0, 'fare': 100.000, 'embarked': 2})

解决方案:

要解决这个问题,可以将要添加的字典放在一个列表中,然后使用 ignore_index=True 参数来忽略索引,示例如下:

data_inicial = pd.DataFrame(columns=['survived', 'pclass', 'sex', 'age', 'sibsp', 'parch', 'fare', 'embarked'])

Rose_infor = [1, 1, 'female', 20, 1, 0, 100.000, 'S']

data_inicial = data_inicial.append({'survived': 0, 'pclass': 3, 'sex': 1, 'age': 23, 'sibsp': 1, 'parch': 0, 'fare': 5.0000, 'embarked': 2}, ignore_index=True)
data_inicial = data_inicial.append({'survived': 1, 'pclass': 1, 'sex': 0, 'age': 20, 'sibsp': 1, 'parch': 0, 'fare': 100.000, 'embarked': 2}, ignore_index=True)

这样就可以成功向 DataFrame 中添加新的行了。

总结:

append() 方法只能接受一个字典作为参数,如果要添加多个字典,需要将它们放在一个列表中,并使用 ignore_index=True 参数来忽略索引。

Pandas DataFrame append() 方法 TypeError: Can only append a dict if ignore_index=True 错误解决

原文地址: https://www.cveoy.top/t/topic/g99X 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录