python - 将条件应用于分组数据
问题描述
我之前为 R 提出过类似的问题,但我现在正试图在 python 中复制相同的任务。我在这篇文章中得到的解决方案与我正在寻找的解决方案相似。
基本上我需要根据分组数据有条件地创建一个新列。
以下是一些示例数据:
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)
非常感谢任何帮助,谢谢!
解决方案
这是一种使用方法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
推荐阅读
- python - 高斯机制比拉普拉斯机制增加了更多的噪声
- java - API 调用(获取请求)返回“ioctl_ping 失败”错误
- javascript - 通过 Javascript 添加图像
- python - 返回 JSON 时,Flask-Rest-API 仅返回 1 个属性
- r - to.period() 无法正常工作 - 尾随毫秒
- python - 使用字符串列表作为键更新嵌套 JSON 文件中的单个值
- reactjs - React-Typescript 中非对象变量的“对象可能未定义”错误
- python - 如何错误处理 discord.py 中的 spotify 命令?
- matlab - 在 MATLAB 中使用 readmatrix 加载多个 Excel 文件
- python - 在数据框中创建一个新列,该列添加具有与另一列对应的更改的值