pandas 将panda列数据从元组列表转换为字典

utugiqy6  于 2022-12-02  发布在  其他
关注(0)|答案(4)|浏览(197)

我正在尝试将Pandas Dataframe 列值从-

{'01AB': [("ABC", 5),("XYZ", 4),("LMN", 1)], '02AB_QTY': [("Other", 20),("not_Other", 150)]}

这就是我一直尝试到现在,但没有工作

import pandas as pd

df = pd.DataFrame.from_records([{'01AB': [("ABC", 5),("XYZ", 4),("LMN", 1)], '02AB_QTY': [("Other", 20),("not_Other", 150)]}])
col_list = ["01AB", "02AB_QTY",]

# for col in col_list:
#     df[col] = df[col].apply(lambda x: {} if x is None else {key: {v[0]:v[1] for v in list_item} for key, list_item in x.items()})

df

预期输出如下所示

{'01AB': {"ABC":5,"XYZ":4,"LMN":1}, '02AB_QTY': {"Other":20,"not_Other":150}}
mbyulnm0

mbyulnm01#

我们可以使用df.applymap(),通过dict解析将每个列表转换为dict,如下所示:

df[col_list] = df[col_list].applymap(lambda lst: {k: v for k, v in lst})
vngu2lb8

vngu2lb82#

import pandas as pd

df = pd.DataFrame.from_records([{'01AB': [("ABC", 5),("XYZ", 4),("LMN", 1)], '02AB_QTY': [("Other", 20),("not_Other", 150)]}])

out_dict = dict()
for col in df.columns:
    out_dict[col] = dict(df[col][0])

输出量:

{'01AB': {'ABC': 5, 'XYZ': 4, 'LMN': 1},
 '02AB_QTY': {'Other': 20, 'not_Other': 150}}
6l7fqoea

6l7fqoea3#

你可以用字典理解:

out = {k: dict(x) for k,v in df.iloc[0].to_dict().items()}

输出量:

{'01AB': {'ABC': 5, 'XYZ': 4, 'LMN': 1},
 '02AB_QTY': {'ABC': 5, 'XYZ': 4, 'LMN': 1}}
baubqpgj

baubqpgj4#

感谢所有的线索,我能够解决如下问题-

import pandas as pd

df = pd.DataFrame.from_records([{'01AB': [("ABC", 5),("XYZ", 4),("LMN", 1)], '02AB_QTY': [("Other", 20),("not_Other", 150)]}])

col_list = ["01AB", "02AB_QTY",]

print(df)

for col in col_list:
    df[col] = df[col].apply(lambda x: {} if x is None else dict(x))

print(df)

输出-

01AB                            02AB_QTY
{'ABC': 5, 'XYZ': 4, 'LMN': 1}  {'Other': 20, 'not_Other': 150}

相关问题