选项1非常简单。只是
set_index
+
sort_index
:
option1 = t.set_index(['land','id']).sort_index()
输出:
area info
land id
A a 123 Im
b 123 gonna
c 23 give
B a 234 never
c 342 you
C c 12 up
选项2有点棘手。一种方法是使用
groupby.apply
应用一个自定义函数
id
她和谁在一起
area
和
info
每人
land
:
def combine(x):
return '; '.join(f'{i}:{j}' for i,j in x) if len(x) > 1 else f'{x[0][1]}'
tmp = t.groupby('land').apply(lambda x: [combine(list(enumerate(x['id'], 1))),
combine(x[['id','area']].to_numpy()),
combine(x[['id','info']].to_numpy())])
option2 = pd.DataFrame(tmp.tolist(), index=tmp.index, columns=['id','area','info'])
输出:
id area info
land
A 1:a; 2:b; 3:c a:123; b:123; c:23 a:Im; b:gonna; c:give
B 1:a; 2:c a:234; c:342 a:never; c:you
C c 12 up