生成包含模态值的新列

时间:2019-07-15 13:35:43

标签: python pandas dataframe pandas-groupby mode

我有以下数据框:

func applicationWillResignActive(_ application: UIApplication) {
    UIScreen.main.brightness = 0.5
}

如何创建另一个像这样的列skus = [1, 1, 1, 2, 2] prices = [10.99, 10.99, 11.50, 9.99, 9.99] data = dict(skus=skus, prices=prices) df = pd.DataFrame(data, columns=data.keys())

prices_mode

即这是每个唯一 skus prices prices_modal 0 1 10.99 10.99 1 1 10.99 10.99 2 1 11.50 10.99 3 2 9.99 9.99 4 2 9.99 9.99 值的价格模式。

1 个答案:

答案 0 :(得分:4)

方法1

使用groupbytransformpd.Series.mode

df['prices_modal'] = df.groupby('skus')['prices'].transform(lambda x: pd.Series.mode(x)[0])

   skus  prices  prices_modal
0     1   10.99         10.99
1     1   10.99         10.99
2     1   11.50         10.99
3     2    9.99          9.99
4     2    9.99          9.99

方法2

使用statistics.mode

from statistics import mode

df['prices_modal'] = df.groupby('skus')['prices'].transform(mode)

   skus  prices  prices_modal
0     1   10.99         10.99
1     1   10.99         10.99
2     1   11.50         10.99
3     2    9.99          9.99
4     2    9.99          9.99