Python Pandas:如何在数据帧的列中拆分排序字典

2023-12-21

我有一个像这样的数据框:

id  asn      orgs
0   3320    {'Deutsche Telekom AG': 2288}
1   47886   {'Joyent': 16, 'Equinix (Netherlands) B.V.': 7}
2   47601   {'fusion services': 1024, 'GCE Global Maritime':16859}  
3   33438   {'Highwinds Network Group': 893}

我想对“orgs”列进行排序,它实际上是一个字典,然后提取两个不同列中具有最高值的对(k,v)。像这样:

id  asn      org                      value
0   3320    'Deutsche Telekom AG'     2288
1   47886   'Joyent'                  16
2   47601   'GCE Global Maritime'     16859 
3   33438   'Highwinds Network Group' 893

目前我正在运行此代码,但它无法正确排序,然后我不确定如何提取具有最高值的对。

df.orgs.apply(lambda x : sorted(x.items(),key=operator.itemgetter(1),reverse=True))

这给了我一个这样的列表:

id  asn      orgs
0   3320    [('Deutsche Telekom AG', 2288)]
1   47886   [('Joyent', 16),( 'Equinix (Netherlands) B.V.', 7)]
2   47601   [('GCE Global Maritime',16859),('fusion services', 1024)]   
3   33438   [('Highwinds Network Group', 893)]

现在我怎样才能将键和最高的值放入两个单独的列中?有人可以帮忙吗?


另一种方法定义一个只调用的函数min在字典上并返回一个系列,以便您可以分配给多个列(函数体取自@亚历克斯·马泰利的回答 https://stackoverflow.com/questions/3282823/get-key-with-the-least-value-from-a-dictionary):

In [17]:

def func(x):
    k = min(x, key=x.get)
    return pd.Series([k, x[k]])
df[['orgs', 'value']] = df['orgs'].apply(func)
df

Out[17]:
     asn  id                        orgs  value
0   3320   0         Deutsche Telekom AG   2288
1  47886   1  Equinix (Netherlands) B.V.      7
2  47601   2             fusion services   1024
3  33438   3     Highwinds Network Group    893

EDIT

如果你的数据有空的dicss,那么你可以只测试len:

In [34]:

df = pd.DataFrame({'id':[0,1,2,3,4],
                   'asn':[3320,47886,47601,33438,56],
                   'orgs':[{'Deutsche Telekom AG': 2288},
                           {'Joyent': 16, 'Equinix (Netherlands) B.V.': 7},
                           {'fusion services': 1024, 'GCE Global Maritime':16859},
                           {'Highwinds Network Group': 893},{}]})
df
Out[34]:
     asn  id                                               orgs
0   3320   0                      {'Deutsche Telekom AG': 2288}
1  47886   1    {'Equinix (Netherlands) B.V.': 7, 'Joyent': 16}
2  47601   2  {'GCE Global Maritime': 16859, 'fusion service...
3  33438   3                   {'Highwinds Network Group': 893}
4     56   4                                                 {}
In [36]:

def func(x):
    if len(x) > 0:
        k = min(x, key=x.get)
        return pd.Series([k, x[k]])
    return pd.Series([np.NaN, np.NaN])

df[['orgs', 'value']] = df['orgs'].apply(func)
df

Out[36]:
     asn  id                        orgs  value
0   3320   0         Deutsche Telekom AG   2288
1  47886   1  Equinix (Netherlands) B.V.      7
2  47601   2             fusion services   1024
3  33438   3     Highwinds Network Group    893
4     56   4                         NaN    NaN
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Python Pandas:如何在数据帧的列中拆分排序字典 的相关文章

随机推荐