python - 在 Python 中,如何像 R 一样进行 group by + mutate + ifelse?

标签 python transform dplyr

我通常使用 R。如果我有这样的数据:

Product    Index   Value
   a         1       0.5
   a         1       0.4
   c         1       1.4
   c         2       0.75
   e         2       0.6
   f         3       0.9

如果我的 R 代码是:

a <- data %>%
  group_by(Product) %>%
  mutate(Flag=ifelse(all(Index==1),'right','wrong'))

这意味着,我首先按产品对数据进行分组。然后对于每个组,我都会给它一个名为 Flag 的新字段。如果本组Index全为1,则Flag正确,否则错误。同时,保留所有记录。所以,结果应该是这样的:

Product    Index   Value    Flag
   a         1       0.5    right
   a         1       0.4    right
   c         1       1.4    wrong
   c         2       0.75   wrong
   e         2       0.6    wrong
   f         3       0.9    wrong

我的问题是:如何在 python 中执行相同的操作?我试过,np.where,groupby,transform等功能。我可能以错误的方式组合它们。

最佳答案

使用转换是一种选择。

import pandas as pd

df = pd.DataFrame({'Product': ['a', 'a', 'c', 'c', 'e', 'f'],
               'Index': [1, 1, 1, 2, 2, 3], 
              'Value': [0.5, 0.4, 1.4, 0.75, 0.6, 0.9]})
df['Flag'] = df.groupby('Product')['Index'].transform(lambda x: 'right' if sum(x)/len(x) == 1 else 'wrong')
df

附带说明一下,如果 Flag 值只是“正确”和“错误”,用 0,1 值替换它们可能更有效。

关于python - 在 Python 中,如何像 R 一样进行 group by + mutate + ifelse?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49973323/

相关文章:

python - Numpy - 仅更改数组一列的值的更简单方法?

c# - 在调整大小时调整 silverlight Canvas 中所有元素的最佳方法是什么?

r - 使用 dplyr 分解不同年份的数据

xml - 从 XSLT 中删除属性并处理结果集

r - 使用 dplyr 中的 mutate_each 函数时选择特定列

r - 多个列表上多个变量的统计检验(tibble)

python - 从 azure blob 存储下载文件的替代方法

python - 如何确保Python pandas中的第一个工作周以1开始?

Python 预处理导入

CSS 变换元素