【问题标题】:Python Pandas, how to group list of dict and sortPython Pandas,如何对字典列表进行分组和排序
【发布时间】:2020-01-16 09:57:58
【问题描述】:

我有一个像这样的字典列表:

data = [
    {'ID': '000681', 'type': 'B:G+',  'testA': '11'},
    {'ID': '000682', 'type': 'B:G+',  'testA': '-'},
    {'ID': '000683', 'type': 'B:G+',  'testA': '13'},
    {'ID': '000684', 'type': 'B:G+',  'testA': '14'},
    {'ID': '000681', 'type': 'B:G+',  'testB': '15'},
    {'ID': '000682', 'type': 'B:G+',  'testB': '16'},
    {'ID': '000683', 'type': 'B:G+',  'testB': '17'},
    {'ID': '000684', 'type': 'B:G+',  'testB': '-'}
]

如何使用 Pandas 获取如下数据:

data = [
    {'ID': '000683', 'type': 'B:G+',  'testA': '13',  'testB': '17'},
    {'ID': '000681', 'type': 'B:G+',  'testA': '11',  'testB': '15'},
    {'ID': '000684', 'type': 'B:G+',  'testA': '14',  'testB': '-'},
    {'ID': '000682', 'type': 'B:G+',  'testA': '-',  'testB': '16'}

]

相同的ID 和相同的type 到一个列,并按testAtestB 值排序

排序:testAtestB 在顶部都有 testA+testB 的值和较大的值。

【问题讨论】:

    标签: python database pandas bigdata


    【解决方案1】:

    首先将列转换为数字,将非数字替换为整数,然后聚合sum

    df = pd.DataFrame(data)    
    c = ['testA','testB']
    df[c] = df[c].apply(lambda x: pd.to_numeric(x, errors='coerce'))
    
    df1 = df.groupby(['ID','type'])[c].sum(min_count=1).sort_values(c).fillna('-').reset_index()
    print (df1)
           ID  type testA testB
    0  000681  B:G+    11    15
    1  000683  B:G+    13    17
    2  000684  B:G+    14     -
    3  000682  B:G+     -    16
    

    如果想按两列之和排序,请使用Series.argsort:

    df = pd.DataFrame(data)
    c = ['testA','testB']
    df[c] = df[c].apply(lambda x: pd.to_numeric(x, errors='coerce'))
    
    df2 = df.groupby(['ID','type'])[c].sum(min_count=1)
    df2 = df2.iloc[(-df2).sum(axis=1).argsort()].fillna('-').reset_index()
    print (df2)
           ID  type testA testB
    0  000683  B:G+    13    17
    1  000681  B:G+    11    15
    2  000682  B:G+     -    16
    3  000684  B:G+    14     -
    

    【讨论】:

      猜你喜欢
      • 2017-02-20
      • 2015-05-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多