作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在处理带有商品价格的 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
最佳答案
您可以将groupby
+ transform
与value_counts
和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
关于python - 如何在 Pandas 中将byby()。transform()转换为value_counts()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47898768/
我是一名优秀的程序员,十分优秀!