[英]create one dict from list of dicts in DataFrame
我正在努力使用簡單的 lambda 來轉換存儲在 df 列中的嵌套字典列表,但被卡住了。
我的 df 看起來像
index synthkey celldata
0 870322681ffffff [{'3400_251': {'s': -77, 'q': -8}}, {'3400_426': {'s': -116, 'q': -16}}]
0 87032268effffff [{'3400_376': {'s': -97, 'q': -12}}, {'3400_426': {'s': -88, 'q': -12}}]
我想要實現的是這樣:
index synthkey celldata
0 870322681ffffff {'3400_251': {'s': -77, 'q': -8},'3400_426': {'s': -116, 'q': -16}}
我嘗試了多次嘗試,例如:
df['dicts'] = df['celldata'].apply(lambda x: {}.update(*x))
或者
df['dicts'] = df.apply(lambda x: {*x['celldata']})
但這讓我離解決方案還差得很遠。
謝謝!
讓我們試試ChainMap
from collections import ChainMap
df['dicts']=df['celldata'].map(lambda x : dict(ChainMap(*x)))
使用簡單的 for 循環使用merge_dict = {**dict_one, **dict_two}
合並字典。
df = pd.DataFrame([{
'index': 0,
'synthkey': '870322681ffffff',
'celldata': [{'3400_251': {'s': -77, 'q': -8}}, {'3400_426': {'s': -116, 'q': -16}}]
},{
'index': 0,
'synthkey': '87032268effffff',
'celldata': [{'3400_376': {'s': -97, 'q': -12}}, {'3400_426': {'s': -88, 'q': -12}}]
}])
def merge_dicts(list_of_dicts):
out = {}
for elem in list_of_dicts:
out = {**out, **elem}
return out
df['new'] = df['celldata'].apply(merge_dicts)
print(df.head())
# index synthkey celldata \
# 0 0 870322681ffffff [{'3400_251': {'s': -77, 'q': -8}}, {'3400_426...
# 1 0 87032268effffff [{'3400_376': {'s': -97, 'q': -12}}, {'3400_42...
# new
# 0 {'3400_251': {'s': -77, 'q': -8}, '3400_426': ...
# 1 {'3400_376': {'s': -97, 'q': -12}, '3400_426':...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.