gpt4 book ai didi

python - 计算 lambda 函数中上述出现的次数

转载 作者:太空宇宙 更新时间:2023-11-03 20:09:50 24 4
gpt4 key购买 nike

我有一个数据框 df ,其中包含 X 列。我想从 X 中创建一个新列 Y

如果同一行中的 X 为 1,并且上面的 0(也在 X 中)应至少为 n(变量)计数,则 Y 应为 1。如果上面的零小于n,则结果应为“”Y。我尝试了(小时)np.where,但没有成功。我想我需要一个 lambda 函数,但不知道如何开始或研究。

示例 n = 4:

在日期 2018-01-25,结果为 1,因为 X 为 1,并且上面的 0 大于 4。

在 2018 年 1 月 25 日,结果为“”,因为 0 仅高于 3(而不是 4)

 Dates        X    Y (like it should be...)
2018-01-02 0
2018-01-03 0
2018-01-04 0
2018-01-05 0
2018-01-08 0
2018-01-09 0
2018-01-10 0
2018-01-11 0
2018-01-12 0
2018-01-15 0
2018-01-16 0
2018-01-17 0
2018-01-18 0
2018-01-19 0
2018-01-22 0
2018-01-23 0
2018-01-24 0
2018-01-25 1 1
2018-01-29 0
2018-01-30 0
2018-01-31 0
2018-02-02 1
2018-02-05 0
2018-02-06 0
2018-02-07 0
2018-02-08 0
2018-02-09 1 1
2018-02-12 1
2018-02-13 0

最佳答案

我们可以groupby临时列,然后应用条件cumsum + cumcount进行某些条件匹配。

s = (df.assign(var1='x').groupby('var1')['X']
.apply(lambda x : x.ne(x.shift()).ne(0).cumsum()))
# create a temp variable.

df['Count']=df.groupby([df.X,s]).cumcount()+1 # add a Count column.

matches = df.iloc[df.loc[(df['X'] == 1)].index - 1].loc[df['Count'] >= 4].index
# find the index matches and check if the previous row has +4 or more matches

df.loc[matches + 1,'Y'] = 1 # Create your Y column.

df.drop('Count',axis=1,inplace=True) # Drop the Count Column.

print(df[df['Y'] == 1]) # print df
Dates X Y
17 2018-01-25 1 1.0
26 2018-02-09 1 1.0

关于python - 计算 lambda 函数中上述出现的次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58773971/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com