我的数据具有以下形状:
id column1 column2
a x 1
a x 3
a y 3
b y 1
b y 2
我希望得到每个id的最重复值以及它的频率百分比。
id column1 % column2 %
a x 66.6 3 66.6
b y 100.0 N/A N/A
一个特殊情况是当频率相等时,我输出N / A列和百分比。
现在我的解决方案纯粹是使用python词典和列表。但是,我正在努力从DataFrame的角度来看待这个问题。
解决办法:
考虑了组的比率相同的条件,结果应该是NaN:
u = df.groupby('id')
c = ('column1', 'column2')
def helper(group, col):
return (group[col].value_counts(normalize=True, sort=True)
.drop_duplicates(keep=False)
.groupby(level=0).head(1)
.to_frame(f'{col}_%')
.reset_index(level=1))
pd.concat([helper(u, col) for col in c], axis=1)
column1 column1_% column2 column2_%
a x 0.666667 3.0 0.666667
b y 1.000000 NaN NaN








暂无数据