Skip to main content
 首页 » 编程设计

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

2024年10月24日11shanyou

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