我有以下结构的数据框:

mydf:

    Entry   Address         ShortOrdDesc
0   988     Fake Address 1  SC_M_W_3_1
1   989     Fake Address 2  SC_M_W_3_3
2   992     Fake Address 3  nan_2
3   992                     SC_M_G_1_1
4   992                     SC_M_O_1_1


在此df上需要完成一些工作,以合并具有相同Entry的行。对于这些,仅第一行具有地址。我需要将ShortOrdDesc列和地址连接起来。我发现了一个非常有用的链接:

Pandas groupby: How to get a union of strings

为此,我开发了以下功能:

def f(x):
     return pd.Series(dict(A = x['Entry'].sum(),
                        B = x['Address'].sum(),
                        C = "%s" % '; '.join(x['ShortOrdDesc'])))


使用哪个

myobj = ordersToprint.groupby('Entry').apply(f)


这将返回错误:


  TypeError:必须为str,而不是int


查看我的数据,我看不出问题出在哪里,因为我相信在'Entry'的整数上运行.sum()应该可以。

我的代码或方法有什么错误?

最佳答案

我认为某些列是数字的,需要string

因此,使用astype,如果需要删除NaN,请添加dropna

def f(x):
 return pd.Series(dict(A = x['Entry'].sum(),
                    B = ''.join(x['Address'].dropna().astype(str)),
                    C = '; '.join(x['ShortOrdDesc'].astype(str))))

myobj = ordersToprint.groupby('Entry').apply(f)
print (myobj)
          A               B                              C
Entry
988     988  Fake Address 1                     SC_M_W_3_1
989     989  Fake Address 2                     SC_M_W_3_3
992    2976  Fake Address 3  nan_2; SC_M_G_1_1; SC_M_O_1_1


agg的另一种解决方案,但随后需要重命名列:

f = {'Entry':'sum',
      'Address' : lambda x: ''.join(x.dropna().astype(str)),
      'ShortOrdDesc' : lambda x: '; '.join(x.astype(str))}
cols = {'Entry':'A','Address':'B','ShortOrdDesc':'C'}
myobj = ordersToprint.groupby('Entry').agg(f).rename(columns=cols)[['A','B','C']]
print (myobj)
          A               B                              C
Entry
988     988  Fake Address 1                     SC_M_W_3_1
989     989  Fake Address 2                     SC_M_W_3_3
992    2976  Fake Address 3  nan_2; SC_M_G_1_1; SC_M_O_1_1

10-08 06:32
查看更多