簡體   English   中英

Python Pandas:如何在數據框的列中拆分排序的字典

[英]Python Pandas: How to split a sorted dictionary in a column of a dataframe

我有一個像這樣的dataFrame:

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)]

現在如何將密鑰和最高值放入兩個單獨的列中? 有人可以幫忙嗎?

另一種方法是定義一個僅在dict上調用min並返回Series的函數,以便您可以分配給多個列(函數主體取自@Alex Martelli的答案 ):

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

編輯

如果您的數據包含空的dics,那么您可以測試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

這應該工作:

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

In [4]: df.orgs, df['value'] = zip(*df.orgs.apply(lambda x : sorted(x.items(),key=operator.itemgetter(1),reverse=True)[0]))

In [5]: df
Out[5]:
     asn  id                     orgs  value
0   3320   0      Deutsche Telekom AG   2288
1  47886   1                   Joyent     16
2  47601   2      GCE Global Maritime  16859
3  33438   3  Highwinds Network Group    893

我使用zip(* <first element of sorted dict items>)並將它們分配給df.orgsdf.value

對於空字典:

In [3]: df = pd.DataFrame({ 'id' : [0,1,2,3],
   ...:                      'asn' : [3320, 47886, 47601, 33438],
   ...:                      'orgs' : [{'Deutsche Telekom AG': 2288}, {'Joyent': 16, 'Equinix (Netherlands) B.V.': 7}, {'fusion services': 1024, 'GCE Global Maritime':16859}, {}]
   ...:                    })
In [4]: df.orgs.apply(lambda x : sorted(x.items(),key=operator.itemgetter(1),reverse=True)[0] if len(x) else ('',''))
Out[4]:
0     (Deutsche Telekom AG, 2288)
1                    (Joyent, 16)
2    (GCE Global Maritime, 16859)
3                            (, )
Name: orgs, dtype: object

In [5]: df.orgs, df['value'] = zip(*df.orgs.apply(lambda x : sorted(x.items(),key=operator.itemgetter(1),reverse=True)[0] if len(x) else ('','')))

In [6]: df
Out[6]:
     asn  id                 orgs  value
0   3320   0  Deutsche Telekom AG   2288
1  47886   1               Joyent     16
2  47601   2  GCE Global Maritime  16859
3  33438   3

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM