首页 > 解决方案 > 将条件应用于分组数据

问题描述

我之前为 R 提出过类似的问题,但我现在正试图在 python 中复制相同的任务。我在这篇文章中得到的解决方案与我正在寻找的解决方案相似。

在缺少值的列上使用 sapply

基本上我需要根据分组数据有条件地创建一个新列。

以下是一些示例数据:

import pandas as pd

test = pd.DataFrame(data={"Group":[1,1,1,1,1,1,2,2,2,2,2,2],"time": 
[0,1,2,3,4,5,0,1,2,3,4,5],"index": 
[1,1.1,1.4,1.5,1.6,1.67,1,1.4,1.5,1.6,1.93,1.95]})

我现在想创建一个新列“new_index”,它将等于时间 3 之前的索引,但从时间 3 开始以不同的速度增长,比如 10%。所以现在数据看起来像

test2 = pd.DataFrame(data={"Group":[1,1,1,1,1,1,2,2,2,2,2,2],"time": 
[0,1,2,3,4,5,0,1,2,3,4,5],"index": 
[1,1.1,1.4,1.5,1.6,1.67,1,1.4,1.5,1.6,1.93,1.95],"new_index": 
[1,1.1,1.4,1.54,1.694,1.8634,1,1.4,1.5,1.65,1.815,1.9965]})

我尝试了一些这样的代码,但它不起作用

def gr_adj(df):
    if df["time"] <= 2:
        return df["index"]
    else:
        return np.cumprod(df["new_index"])

test["new_index] = test.groupby("Group",group_keys=False).apply(gr_adj)

非常感谢任何帮助,谢谢!

标签: pythonpandasdataframeconditional-statementspandas-groupby

解决方案


这是一种使用方法cumprod,第一个掩码所有时间超过 3 的索引为 1.1 ,然后我们通过不包括我们不需要更新的那个来分割输出,然后我们groupby得到cumprod,然后将其分配回去

s=test['index'].where(test['time']<3,1.1).loc[test['time']>=2].groupby(test['Group']).cumprod()
test.loc[test['time']>=2,'index']=s
test
Out[290]: 
    Group  time   index
0       1     0  1.0000
1       1     1  1.1000
2       1     2  1.4000
3       1     3  1.5400
4       1     4  1.6940
5       1     5  1.8634
6       2     0  1.0000
7       2     1  1.4000
8       2     2  1.5000
9       2     3  1.6500
10      2     4  1.8150
11      2     5  1.9965

推荐阅读