一旦满足条件,请选择连续的行。示例:
dfA :
style day stock
pants mon 0
pants tue 2
pants wed 1
pants thu 0
pants fri 1
pants sat 0
shirt sat 1
shirt thu 2
shirt mon 0
shirt tue 0
shirt wed 2
shirt fri 0选择天数排序后和库存大于0时的连续行
expected output :
pants tue 2
pants wed 1
pants thu 0
pants fri 1
pants sat 0
shirt sat 1
shirt thu 0
shirt wed 2
shirt fri 0所以在裤子方面,一旦库存在周二达到2,我们选择了之后的所有日子,在衬衫中,一旦库存在周三达到2,我们就选择了之后的所有日子。我尝试了按and >0条件分组,但没有得到预期的结果,任何领先都将不胜感激。
发布于 2020-09-29 17:42:19
这里有一个解决方案,它可能不是最优雅的,但它的优点是相当清晰。
在这里,我介绍了具有天id的中间列(以正确的周顺序!)每种款式的第一天都有库存。然后,您只需要比较这两列。
week = ["mon", "tue", "wed", "thu", "fri", "sat"]
fun = lambda x: week.index(x)
a["day_id"] = a["day"].map(fun) # column with day id
first_day = a[a["stock"] > 0].groupby("style")["day_id"].min() # select lines with stock>0 and find first day per style
a["first_day"] = a["style"].map(first_day) # column with first day with stock per style (very redundant)
result = a[a["day_id"] >= a["first_day"]]发布于 2020-09-29 19:35:07
您可以使用以下方法应用分组。创建临时字典以保存结果分组的dfs:
dict_temp = {key: None for key in df["style"].unique()}在满足条件后获取剩余行:
for key in dict_temp:
# get the index of first True of condition (here ==2)
index_fist_true = np.where(df.groupby("style").get_group(key)["stock"]==2)[0][0]
# save the rest of grouped dataframe in dict_temp
dict_temp[key] = df.groupby("style").get_group(key).reset_index()[index_fist_true+1:]连接dict_temp的值并对其进行转换:
pd.concat(dict_temp.values()).drop("index", axis=1).reset_index(drop=True)https://stackoverflow.com/questions/64116553
复制相似问题