【问题标题】:Expand pandas dataframe column of dict into dataframe columns [duplicate]将dict的pandas数据框列扩展为数据框列[重复]
【发布时间】:2019-06-18 00:56:29
【问题描述】:

我有一个 Pandas DataFrame,其中一列是一系列字典,如下所示:

   colA  colB                                  colC
0     7     7  {'foo': 185, 'bar': 182, 'baz': 148}
1     2     8  {'foo': 117, 'bar': 103, 'baz': 155}
2     5    10  {'foo': 165, 'bar': 184, 'baz': 170}
3     3     2  {'foo': 121, 'bar': 151, 'baz': 187}
4     5     5  {'foo': 137, 'bar': 199, 'baz': 108}

我希望 dicts 中的 foobarbaz 键值对成为我的数据框中的列,这样我就得到了这样的结果:

   colA  colB  foo  bar  baz
0     7     7  185  182  148
1     2     8  117  103  155
2     5    10  165  184  170
3     3     2  121  151  187
4     5     5  137  199  108

我该怎么做?

【问题讨论】:

  • 我不确定这个问题是否与标记的问题重复。这似乎是关于将 to 字典转换为将数据从字典中返回到原始数据帧
  • @Phil .. OP 没有表现出努力,这是关闭此问题的原因之一。阅读:“家庭作业”。指针 -> 书籍:VanderPlas:Python 数据科学手册。 EOR。
  • 刚刚投票决定重新开放......我们会看看会发生什么。

标签: python pandas dictionary dataframe series


【解决方案1】:

TL;DR

df = df.drop('colC', axis=1).join(pd.DataFrame(df.colC.values.tolist()))

详细回答

我们首先定义要使用的 DataFrame,以及导入 Pandas:

import pandas as pd


df = pd.DataFrame({'colA': {0: 7, 1: 2, 2: 5, 3: 3, 4: 5},
                   'colB': {0: 7, 1: 8, 2: 10, 3: 2, 4: 5},
                   'colC': {0: {'foo': 185, 'bar': 182, 'baz': 148},
                    1: {'foo': 117, 'bar': 103, 'baz': 155},
                    2: {'foo': 165, 'bar': 184, 'baz': 170},
                    3: {'foo': 121, 'bar': 151, 'baz': 187},
                    4: {'foo': 137, 'bar': 199, 'baz': 108}}})

colC 列是 dicts 的pd.Series,我们可以通过将每个 dict 转换为 pd.Series 来将其转换为 pd.DataFrame

pd.DataFrame(df.colC.values.tolist())
# df.colC.apply(pd.Series). # this also works, but it is slow

给出pd.DataFrame:

   foo  bar  baz
0  154  190  171
1  152  130  164
2  165  125  109
3  153  128  174
4  135  157  188

所以我们需要做的就是:

  1. colC 变成pd.DataFrame
  2. df中删除原来的colC
  3. 加入转换 colCdf

这可以在单行中完成:

df = df.drop('colC', axis=1).join(pd.DataFrame(df.colC.values.tolist()))

df 的内容现在是pd.DataFrame

   colA  colB  foo  bar  baz
0     2     4  154  190  171
1     4    10  152  130  164
2     4    10  165  125  109
3     3     8  153  128  174
4    10     9  135  157  188

【讨论】:

  • 不,这是一个缓慢的解决方案,不推荐使用.apply(pd.Series),与列表类似的解决方案 - 检查来自this的时间
  • 对不起,错误的欺骗,现在添加正确。
  • 我改为回答使用pd.DataFrame(df.colC.values.tolist()),尽管我仍然提到apply-方法作为较慢的替代方案。
  • 是的,这是更好的解决方案,但不幸的是被骗了:(
  • 好吧,我写它是因为我从来没有找到一个清晰的 stackoverflow 教程来扩展和替换一个 columnd-of-dicts,所以希望有人会偶然发现这个,即使是他们被重定向到“原始”答案:)感谢您对性能问题的提醒。
猜你喜欢
  • 2021-04-02
  • 2021-04-22
  • 2017-05-02
  • 2017-04-01
  • 1970-01-01
  • 2014-10-15
  • 1970-01-01
  • 1970-01-01
  • 2018-12-02
相关资源
最近更新 更多