如何在 pandas 中将byby().transform()转换为value_counts()? [英] How to groupby().transform() to value_counts() in pandas?
本文介绍了如何在 pandas 中将byby().transform()转换为value_counts()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在处理带有商品价格的熊猫数据框 df1
.
I am processing a pandas dataframe df1
with prices of items.
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)
如何创建最低共同价
?
df1["Minimum"] = df1.groupby(["Item"])['Price'].transform(value_counts()) # Doesn't work
此刻,我使用多步骤方法:
In the moment, I use a multi-step approach:
for item in df1.Item.unique().tolist(): # Pseudocode
df1 = df1[df1.Price == Item] # Pseudocode
df1.Price.value_counts().max() # Pseudocode
这太过分了.必须有一种更简单的方法,理想情况下是一行
which is overkill. There must be a more simple way, ideally in one line
如何在熊猫中将byby().transform()转换为value_counts()?
推荐答案
您可以对 value_counts
和使用
. groupby
+ transform
idxmax
You could use groupby
+ transform
with value_counts
and idxmax
.
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
这篇关于如何在 pandas 中将byby().transform()转换为value_counts()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文