gpt4 book ai didi

python - 根据条件转换数据框的列

转载 作者:太空宇宙 更新时间:2023-11-04 09:49:10 25 4
gpt4 key购买 nike

每当说唱等于 1 时,我也愿意添加一个包含三个连续 1 的新列。三个连续的 1 必须在同一年,当 rap 等于 one 和之前的两个时。新列必须按 ID(我有一个数据面板)。

df 看起来像这样:

id  year  rap  cohort  jobs  year_of_life  
1 2009 0 NaN 10 NaN
1 2012 0 2012 12 0
1 2013 0 2012 12 1
1 2014 0 2012 13 2
1 2015 1 2012 15 3
1 2016 0 2012 17 4
1 2017 0 2012 18 5
2 2009 0 2009 15 0
2 2010 0 2009 2 1
2 2011 0 2009 3 2
2 2012 1 2009 3 3
2 2013 0 2009 15 4
2 2014 0 2009 12 5
2 2015 0 2009 13 6
2 2016 0 2009 13 7

预期输出:

id  year  rap  cohort  jobs  year_of_life  rap_new
1 2009 0 NaN 10 NaN 0
1 2012 0 2012 12 0 0
1 2013 0 2012 12 1 1
1 2014 0 2012 13 2 1
1 2015 1 2012 15 3 1
1 2016 0 2012 17 4 0
1 2017 0 2012 18 5 0
2 2009 0 2009 15 0 0
2 2010 0 2009 2 1 1
2 2011 0 2009 3 2 1
2 2012 1 2009 3 3 1
2 2013 0 2009 15 4 0
2 2014 0 2009 12 5 0
2 2015 0 2009 13 6 0
2 2016 0 2009 13 7 0

最佳答案

这是一种方式。

# calculate rap_new indices
rap_indices = [i for i, j in enumerate(df.rap) if j==1]
rap_new_indices = list(set.union(*[set(range(n-2, n+1)) for n in rap_indices]))

# apply indices to new col
df.rap_new = 0
df.loc[rap_new_indices, 'rap_new'] = 1

# id year rap cohort jobs year_of_life rap_new
# 0 1 2009 0 NaN 10 NaN 0
# 1 1 2012 0 2012.0 12 0.0 0
# 2 1 2013 0 2012.0 12 1.0 1
# 3 1 2014 0 2012.0 13 2.0 1
# 4 1 2015 1 2012.0 15 3.0 1
# 5 1 2016 0 2012.0 17 4.0 0
# 6 1 2017 0 2012.0 18 5.0 0
# 7 2 2009 0 2009.0 15 0.0 0
# 8 2 2010 0 2009.0 2 1.0 1
# 9 2 2011 0 2009.0 3 2.0 1
# 10 2 2012 1 2009.0 3 3.0 1
# 11 2 2013 0 2009.0 15 4.0 0
# 12 2 2014 0 2009.0 12 5.0 0
# 13 2 2015 0 2009.0 13 6.0 0
# 14 2 2016 0 2009.0 13 7.0 0

关于python - 根据条件转换数据框的列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48553276/

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