【问题标题】:Python Pandas, one dict column, create new rows for each key/value pairPython Pandas,一个 dict 列,为每个键/值对创建新行
【发布时间】:2016-07-13 01:48:24
【问题描述】:

我有一个大约 500000 行的 Pandas DataFrame,格式如下:

**ID  Name  Tags**
4345  Bill  {'circle:blue', 'background:orange', 'Type':12}

为了更直接的数据分析,我想转换为:

**ID   Name  Key         Value** 
4345   Bill  Circle      Blue
4345   Bill  Background  Orange
4345   Bill  Type        12

我找到了一个可以每行拆分一个键/值的答案: Python Pandas: How to split a sorted dictionary in a column of a dataframe,但我很遗憾地未能扩展它来执行我的上述要求。

我或许可以使用一些标准循环来处理这个问题,但我希望有一种优雅高效的 Pandas 方法?

【问题讨论】:

    标签: python dictionary pandas


    【解决方案1】:

    基于this answer,你可以做类似的事情:

    >>> df_tags = df.apply(lambda x: pd.Series(x['Tags']),axis=1).stack().reset_index(level=1, drop=False)
    >>> df_tags.columns = ['Key', 'Value']
    >>> df_tags
              Key   Value
    0        Type      12
    0  background  orange
    0      circle    blue
    >>> df.drop('Tags', axis=1).join(df_tags)
         ID  Name         Key   Value
    0  4345  Bill        Type      12
    0  4345  Bill  background  orange
    0  4345  Bill      circle    blue
    

    【讨论】:

    • 该解决方案适用于小型测试数据集,但我的计算机在 0.5M 行表上崩溃了。我已经恢复到在 Postgresql 中执行此操作并将结果导入 Pandas。
    猜你喜欢
    • 2023-04-01
    • 1970-01-01
    • 2018-07-16
    • 1970-01-01
    • 1970-01-01
    • 2021-10-17
    • 1970-01-01
    • 2015-01-31
    相关资源
    最近更新 更多