gpt4 book ai didi

python - 如何在 Pandas 中将byby()。transform()转换为value_counts()?

转载 作者:行者123 更新时间:2023-12-04 22:55:43 25 4
gpt4 key购买 nike

我正在处理带有商品价格的 Pandas 数据框df1

  Item    Price  Minimum Most_Common_Price
0 Coffee 1 1 2
1 Coffee 2 1 2
2 Coffee 2 1 2
3 Tea 3 3 4
4 Tea 4 3 4
5 Tea 4 3 4

我使用以下方法创建 Minimum:
df1["Minimum"] = df1.groupby(["Item"])['Price'].transform(min)

如何创建 Most_Common_Price
df1["Minimum"] = df1.groupby(["Item"])['Price'].transform(value_counts()) # Doesn't work

目前,我使用多步骤方法:
for item in df1.Item.unique().tolist(): # Pseudocode
df1 = df1[df1.Price == Item] # Pseudocode
df1.Price.value_counts().max() # Pseudocode

这太过分了。必须有一种更简单的方法,理想情况下是一行

如何在 Pandas 中将groupby()。transform()转换为value_counts()?

最佳答案

您可以将groupby + transformvalue_countsidxmax一起使用。

df['Most_Common_Price'] = (
df.groupby('Item')['Price'].transform(lambda x: x.value_counts().idxmax()))

df

Item Price Minimum Most_Common_Price
0 Coffee 1 1 2
1 Coffee 2 1 2
2 Coffee 2 1 2
3 Tea 3 3 4
4 Tea 4 3 4
5 Tea 4 3 4

一项改进涉及 pd.Series.map的使用,
# Thanks, Vaishali!
df['Item'] = (df['Item'].map(df.groupby('Item')['Price']
.agg(lambda x: x.value_counts().idxmax()))
df

Item Price Minimum Most_Common_Price
0 Coffee 1 1 2
1 Coffee 2 1 2
2 Coffee 2 1 2
3 Tea 3 3 4
4 Tea 4 3 4
5 Tea 4 3 4

关于python - 如何在 Pandas 中将byby()。transform()转换为value_counts()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47898768/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com