1 回答

TA貢獻(xiàn)1829條經(jīng)驗(yàn) 獲得超4個(gè)贊
我不確定您的原始代碼有什么問(wèn)題,但這是一種解決方案:
import pandas as pd
from itertools import chain
>>>df
Service1 Service2 Service3 Service10
ID
1 A B C Z
1 B C D Y
1 A B C O
2 R S T B
df_regsvc = df.groupby(df.index)['Service1','Service2','Service3','Service10'] \
.apply(lambda x : list(chain.from_iterable([*x.values]))) \
.apply(lambda x: max(x, key=x.count)).to_frame()
>>>df_regsvc
ID
1 B
2 R
dtype: object
# Join it with the aggregate for the Premium column
df_premium = df.groupby(df.index)['Premium'].agg(lambda x: pd.Series.mode(x)[0]).to_frame()
df_agg = df_regsvc.join(df_premium)
>>>df_agg
0 Premium
ID
1 B XX
2 R XX
添加回答
舉報(bào)