python - python中不同列中列内的字典的拆分列表

标签 python python-3.x pandas dictionary

我有一个像这样的数据框

data = {'col_1': [1, 2],
        'col_2': [[{'KEY': 'A', 'VALUE': 'a'}], [{'KEY': 'B', 'VALUE': 'b'}]],
        'col_3': [[{'KEY': 'C', 'VALUE': 'c'}], [{'KEY': 'A', 'VALUE': 'a'}]]}
pd.DataFrame.from_dict(data)

    col_1   col_2                           col_3
0   1       [{'KEY': 'A', 'VALUE': 'a'}]    [{'KEY': 'C', 'VALUE': 'c'}]
1   2       [{'KEY': 'B', 'VALUE': 'b'}]    [{'KEY': 'A', 'VALUE': 'a'}]

我想转换每列中的字典列表,以便得到以下输出

    col_1   col_2_KEY   col_2_VALUE     col_3_KEY   col_3_VALUE
0   1       A           a               C           c
1   2       B           b               A           a

编辑1:

可能存在列值为空的情况

data = {'col_1': [1, 2],
        'col_2': [[{'KEY': 'A', 'VALUE': 'a'}], [{'KEY': 'B', 'VALUE': 'b'}]],
        'col_3': [[{'KEY': 'C', 'VALUE': 'c'}], [{'KEY': 'A', 'VALUE': 'a'}]]}
pd.DataFrame.from_dict(data)

    col_1   col_2                           col_3
0   1       [{'KEY': 'A', 'VALUE': 'a'}]    []
1   2       [{'KEY': 'B', 'VALUE': 'b'}]    [{'KEY': 'A', 'VALUE': 'a'}]

预期输出

    col_1   col_2_KEY   col_2_VALUE     col_3_KEY   col_3_VALUE
0   1       A           a               <blank>     <blank> 
1   2       B           b               A           a

最佳答案

你可以尝试:

df = pd.concat([df.drop(['col_2','col_3'], axis=1)
                , df['col_2'].apply(lambda x:pd.Series(x[0] if len(x)>0 else {})).rename(columns={'KEY':'col_2_KEY','VALUE':'col_2_VALUE'})
                , df['col_3'].apply(lambda x:pd.Series(x[0] if len(x)>0 else {})).rename(columns={'KEY':'col_3_KEY','VALUE':'col_3_VALUE'})
                ], axis=1)
print(df)

   col_1 col_2_KEY col_2_VALUE col_3_KEY col_3_VALUE
0      1         A           a         C           c
1      2         B           b         A           a

关于python - python中不同列中列内的字典的拆分列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55116169/

相关文章:

python - 在 Pandas 中,如何复制列中具有特定值的所有行,并更改重复项中的该列值?

python - 循环之神再次来袭——如何在 GUI mainloop 的情况下保持套接字连接?

python - pip 安装并运行 git repo

python - 如何在输入函数中引用变量?

python - python3.x中根据另一个列表中的子字符串列表删除列表中的项目

python - ASYNC - Pandas read_sql 和 asyncio?

python - 时间戳字符串(Unix 时间)到日期时间或 pandas.Timestamp

Python方法对url的 "non-standard"部分进行引用

python - python代码错误

python - 我在 python 中创建列表列表时遇到问题