Python Pandas,一个字典列,为每个键/值对创建新行

标签 python dictionary pandas

我有一个包含大约 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 方法?

最佳答案

基于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

关于Python Pandas,一个字典列,为每个键/值对创建新行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36217666/

相关文章:

javascript - Python - 从数组中提取元素,类似于 JavaScript ES6 解构

python - 计算 pandas/python 中 df 的一列中非零数字的数量

python - 从在错误目录中创建的 latex 代码生成的 pdf 文件 - Python

python - 如何正确地将 Python 可执行文件上传到 GitHub?

python - 如何在 python 中使用 Selenium 和 Beautifulsoup 解析网站?

python - 如何更新pyqt中的图表之类的东西

python - 如何根据字典键和值过滤 Pandas 数据框行?

Java map 迭代

python - 无法迭代 PyTorch DataLoader

python - 如何在 Python 中从生成表格的网站进行网页抓取?