本文介绍了如何通过不同的字典将df扩展为列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有 different 格的df作为一列中的条目,在我的情况下为信息"列.我想通过所有可能的dict.keys()扩展df,如下所示:

I have a df with different dicts as entries in a column, in my case column "information". I would like to expand the df by all possible dict.keys(), something like that:

import pandas as pd
import numpy as np
df = pd.DataFrame({'id': pd.Series([1, 2, 3, 4, 5]),
                   'name': pd.Series(['banana',
                                      'apple',
                                      'orange',
                                      'strawberry' ,
                                      'toast']),
                   'information': pd.Series([{'shape':'curve','color':'yellow'},
                                             {'color':'red'},
                                             {'shape':'round'},
                                             {'amount':500},
                                             np.nan]),
                   'cost': pd.Series([1,2,2,10,4])})


   id        name                            information  cost
0   1      banana  {'shape': 'curve', 'color': 'yellow'}     1
1   2       apple                       {'color': 'red'}     2
2   3      orange                     {'shape': 'round'}     2
3   4  strawberry                        {'amount': 500}    10
4   5       toast                                    NaN     4

应如下所示:

   id        name  shape   color  amount  cost
0   1      banana  curve  yellow     NaN     1
1   2       apple    NaN     red     NaN     2
2   3      orange  round     NaN     NaN     2
3   4  strawberry    NaN     NaN   500.0    10
4   5       toast    NaN     NaN     NaN     4

推荐答案

另一种方法是使用pandas.DataFrame.from_records:

import pandas as pd

new = pd.DataFrame.from_records(df.pop('information').apply(lambda x: {} if pd.isna(x) else x))
new = pd.concat([df, new], 1)
print(new)

输出:

   cost  id        name  amount   color  shape
0     1   1      banana     NaN  yellow  curve
1     2   2       apple     NaN     red    NaN
2     2   3      orange     NaN     NaN  round
3    10   4  strawberry   500.0     NaN    NaN
4     4   5       toast     NaN     NaN    NaN

这篇关于如何通过不同的字典将df扩展为列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-02 13:05