大佬教程收集整理的这篇文章主要介绍了如何从 Pandas 列内的多个嵌套字典中自动提取数据?,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个 Pandas dd,其中的列是由字典组成的,其中一些字典里面有更多的字典:
列 country
的示例行:
{'conTinent': 'EU','official_name': 'Spain','cAPItal': 'MadrID','name': 'Spain','Alpha2': 'ES','Alpha3': 'ESP','numeric': '724','currency': {'symbol': '€','code': 'EUR','name': 'Euro','numeric': '978'},'locale': 'es-ES','phone_prefix': '34'}
我已经编写了一些代码来将这些字典提取到新的 df 列中:
# Dictionariy that contains the names of the columns and their data types
sub_obj_types = {Col: set(map(type,first_clean_df[col])) for col in first_clean_df.SELEct_dtypes(include=[object])}
# Filter out those columns which have not any DictionarIEs insIDe
second_Dict_cols = {k:v for k,v in sub_obj_types.items() if next(iter(v)) == Dict}.keys()
# Empty Dict where we'll store the keys of the DictionarIEs of each column
subkeys = {}
# Get the key names of each column's Dictionary and store them in the Dict
for col in second_Dict_cols:
subkeys[col] = List(first_clean_df[col][0].keys())
# Empty List where we'll store each column
sub_serIEs_List = []
# Iterate over the keys
for k in subkeys:
# IIterate over the values
for v in subkeys[k]:
# Iterate over each column of the table and get the information out of the Dict into a new column
serIEs = first_clean_df[k].apply(lambda x: x[v] if isinstance(x,Dict) else type(X))
# Change the column name
serIEs.name = v
# Store the column in the List
sub_serIEs_List.append(serIEs)
# Concatenate all the columns horizontally and build a new df
clean_df = pd.concat(sub_serIEs_List,axis = 1)
这是我按照这些步骤后得到的:
该表比这大得多,我无法包含它的全貌,但基本上这个想法是我正在从包含在多个列中的每个字典的每个键中创建一个新列。
问题是,正如你在照片中看到的,在清理步骤之后,新创建的列中有更多的字典,所以我必须在新表上再次重复相同的步骤以创建更多的列那些新的字典,然后我发现有更多的嵌套字典,我必须再次重复它直到完成。
我的问题是,如何使这个过程自动化,使其只运行一次,并将所有嵌套的字典放入新表的新列中,而无需一次又一次地重新运行同一段代码?
非常感谢您提前
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)
以上是大佬教程为你收集整理的如何从 Pandas 列内的多个嵌套字典中自动提取数据?全部内容,希望文章能够帮你解决如何从 Pandas 列内的多个嵌套字典中自动提取数据?所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。