如何将单个字典添加至Pandas Series?解决TypeError报错问题
解决Pandas Series添加字典报错的问题
问题场景
想要创建一个包含字典元素的Series,尝试使用以下代码实现:
import pandas as pd series_structure = pd.Series() for i in table_dtypes[0]: if i == "object": type_dict = {'type': 'categorical'} series_structure.append(type_dict) elif i == "boolean": type_dict = {'type': 'boolean'} series_structure.append(type_dict) elif i == "datetime64": # revisit here type_dict = {'type': 'datetime', 'format': '%Y-%m-%d'} series_structure.append(type_dict) elif i == "int64": type_dict = {'type': 'id', 'subtype': 'integer'} series_structure.append(type_dict) elif i == "float64": # revisit here type_dict = {'type': 'numerical', 'subtype': 'float'} series_structure.append(type_dict)
运行后触发报错:
TypeError: cannot concatenate object of type '<class 'dict'>'; only Series and DataFrame objs are valid
错误原因
pd.Series.append()方法仅支持拼接Series或DataFrame对象,无法直接追加字典类型的数据,这是报错的核心原因。
修复方案
推荐方案:列表收集后一次性创建Series
先将所有字典存入列表,最后用列表生成Series,这种方式效率更高:
import pandas as pd type_list = [] for i in table_dtypes[0]: if i == "object": type_list.append({'type': 'categorical'}) elif i == "boolean": type_list.append({'type': 'boolean'}) elif i == "datetime64": type_list.append({'type': 'datetime', 'format': '%Y-%m-%d'}) elif i == "int64": type_list.append({'type': 'id', 'subtype': 'integer'}) elif i == "float64": type_list.append({'type': 'numerical', 'subtype': 'float'}) series_structure = pd.Series(type_list)
备选方案:将字典转为Series后再追加
如果坚持使用append方式,需要把每个字典包装成Series再进行拼接,但这种方式循环追加会产生较多临时对象,效率较低:
import pandas as pd series_structure = pd.Series(dtype='object') for i in table_dtypes[0]: if i == "object": type_dict = {'type': 'categorical'} series_structure = series_structure.append(pd.Series([type_dict])) elif i == "boolean": type_dict = {'type': 'boolean'} series_structure = series_structure.append(pd.Series([type_dict])) elif i == "datetime64": type_dict = {'type': 'datetime', 'format': '%Y-%m-%d'} series_structure = series_structure.append(pd.Series([type_dict])) elif i == "int64": type_dict = {'type': 'id', 'subtype': 'integer'} series_structure = series_structure.append(pd.Series([type_dict])) elif i == "float64": type_dict = {'type': 'numerical', 'subtype': 'float'} series_structure = series_structure.append(pd.Series([type_dict]))
内容的提问来源于stack exchange,提问作者PineNuts0
相关产品推荐
相关产品推荐

