首页 > 解决方案 > 爆炸具有字典列表的数据框中的 1 列,每个字典应该是一个新列

问题描述

我有一个数据框,其中有一列如下所示:

附件.数据 标题 2
[{'title': '测试标题', 'unshimmed_url': 'https://www.etc.com'}] 34
[{'title': 'This is another Test Title for Testing', 'unshimmed_url': 'https://www.etc2.com'}] 42

并想分开title并使其成为新的列链接unshimmed_url

我已经尝试过了,但我认为我错过了一个步骤,因为我丢失了标题 2 和标题 3 列,现在它只是名称和链接列..

s = df['attachments.data'].explode()
calcu = pd.DataFrame(s.tolist(), index=s.index)
df2 = calcu.rename(columns={'title': 'name', 'unshimmed_url': 'link'})

标签: pandasdataframe

解决方案


popattachments.data以相同的方式创建 DataFrame,但随后join返回df

s = df.pop('attachments.data').explode()
df = df.join(
    pd.DataFrame(s.tolist(), index=s.index)
        .rename(columns={'title': 'name', 'unshimmed_url': 'link'})
)

df

   Heading 2                                    name                  link
0         34                  Test Title for Testing   https://www.etc.com
1         42  This is another Test Title for Testing  https://www.etc2.com

或者不修改df drop并创建一个新的DataFrame:

s = df['attachments.data'].explode()
df2 = df.drop(columns='attachments.data').join(
    pd.DataFrame(s.tolist(), index=s.index)
        .rename(columns={'title': 'name', 'unshimmed_url': 'link'})
)

或者构建新列:apply pd.Series

df2 = df.drop(columns='attachments.data').join(
    df['attachments.data'].explode()
        .apply(pd.Series)
        .rename(columns={'title': 'name', 'unshimmed_url': 'link'})
)

df2

   Heading 2                                    name                  link
0         34                  Test Title for Testing   https://www.etc.com
1         42  This is another Test Title for Testing  https://www.etc2.com

数据框和导入:

import pandas as pd

df = pd.DataFrame({
    'attachments.data': [
        [{'title': 'Test Title for Testing',
          'unshimmed_url': 'https://www.etc.com'}],
        [{'title': 'This is another Test Title for Testing',
          'unshimmed_url': 'https://www.etc2.com'}]],
    'Heading 2': [34, 42]
})

推荐阅读