python - 向 lambda 或函数添加计算
问题描述
我有一个df,例如
ID | Status | Color
555 Cancelled Green
434 Processed Red
212 Cancelled Blue
121 Cancelled Green
242 Cancelled Blue
352 Processed Green
343 Processed Blue
我正在使用如下代码:
cc = df.groupby(by='Color').ID.count()
df.groupby(by=['Color', 'Status']).apply(lambda x: len(x)/cc.loc[x.Color.iloc[0]])
这给了我输出,例如
Color Status
Blue Cancelled 0.666667
Processed 0.333333
Green Cancelled 0.666667
Processed 0.333333
Red Processed 1.000000
dtype: float64
这给了我每种颜色状态的百分比。
还有一个名为Dollar_value的字段,其中每行包含美元金额,如果我想在我的输出中添加两个字段1. Total_Dollars表示该颜色和状态,2. Dollar_per_order表示该颜色(这意味着如果 Total_Dollars 是 1000 并且存在该颜色和状态是 200 行,它将是 1000/200 或 5。我可以轻松地将这两个计算添加到我已经拥有的输出中吗?或者我需要创建一个函数吗?
期望的输出:
Color Status Total |Dollar_Per_Order
Blue Cancelled 0.666667 1000 20
Processed 0.333333 200 5
Green Cancelled 0.666667 2000 20
Processed 0.333333 1000 5
Red Processed 1.000000 300 10
dtype: float64
谢谢!
解决方案
要计算所有 3 列,请将要应用于每个组的函数定义为:
def fn(grp):
total = grp.dollar_value.sum()
rowNo = len(grp.index)
return pd.Series([ rowNo/cc[grp.name[0]], total, total/rowNo ],
index=[ 'Percentage', 'Total_Dollars', 'Dollar_per_order'])
然后应用它:
df.groupby(by=['Color', 'Status']).apply(fn)
请注意,我使用len(grp.index)
而不是len(grp)
. 原因是它运行得更快一些。
除了你之外,我还以其他方式阅读当前组的颜色。
推荐阅读
- python - 法语字符变成问号;熊猫
- regex - 用于忽略某些单词的正则表达式
- python-3.x - 在循环中实例化时,Checkbutton 命令绑定到错误的值
- python - 如何让网站相信请求来自使用 Scrapy 的浏览器?
- firebase - 当显示触发firestore(onUpdate)打字稿错误的firebase云功能时
- python - 如何在 Python/Pandas 中计算连胜
- json - 如何从 JSON 对象中获取特定值,例如名称?
- jdbc - 将 Pentaho 数据集成与 Oracle 自治数据仓库连接起来
- ruby-on-rails - Rails cancancan 获取特定用户的记录
- scala - 如何在 Scala 中将杂乱无章的文本文件转换为 Array[String]?