我有以下数据框:
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
值的价格模式。
答案 0 :(得分:4)
使用groupby
,transform
和pd.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
使用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