【发布时间】:2019-12-23 02:46:38
【问题描述】:
我之前曾针对 R 提出过类似的问题,但我现在正尝试在 python 中复制相同的任务。我在这篇文章中得到的解决方案与我正在寻找的解决方案相似。
Using sapply on column with missing values
基本上我需要根据分组数据有条件地创建一个新列。
以下是一些示例数据:
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)
非常感谢任何帮助,谢谢!
【问题讨论】:
-
时间列中的值是否循环且始终有序?
-
@SMir 是的,每个组的时间行数相同,并且它们是有序的
标签: python pandas dataframe conditional-statements pandas-groupby