首页 > 解决方案 > increment number in this list comprehension

问题描述

Consider the following DF.

   ID   Name    Week    Course        Hours
0   1   John A  1922    Bike Tech     5.5
1   2   John B  1922    Auto Tech     3.2
2   3   John C  1922    Prison        3.5
3   4   John D  1922    Comp          6.5
4   5   John E  1922    Awareness     7.0
5   6   John F  1922    First Aid     7.2
6   7   John G  1922    BasketBall    2.5
7   8   John H  1922    Tech          5.4

I'm using the following code to duplicate rows

duplicate = [3 if val == 'Prison' else 1 for val in df.Course]

which is great, but I need to increment the Week Number for every duplication so John C would have 3 rows with Week 1922, 1923 and 1924.

I've tried

[3 if val == 'Prison' and df.Week +1 else 1 for val in df.Course]

and a few other basic chains but I can't figure this out.

  ID   Name    Week    Course        Hours
0   1   John A  1922    Bike Tech     5.5
1   2   John B  1922    Auto Tech     3.2
2   3   John C  1922    Prison        3.5
2   3   John C  1923    Prison        3.5
2   3   John C  1924    Prison        3.5
3   4   John D  1922    Comp          6.5
4   5   John E  1922    Awareness     7.0
5   6   John F  1922    First Aid     7.2
6   7   John G  1922    BasketBall    2.5
7   8   John H  1922    Tech          5.4 

标签: pythonpandas

解决方案


If I understand correctly, you could just create a helper dataframe of the rows you want duplicated, then increment the Week number on that helper dataframe, then concatenate to your original:

helper = pd.concat([df.loc[df.Course == 'Prison']]*2)
helper['Week'] += helper.reset_index().index+1

df = pd.concat((df,helper)).sort_values('ID')

>>> df
   ID    Name  Week      Course  Hours
0   1  John A  1922   Bike Tech    5.5
1   2  John B  1922   Auto Tech    3.2
2   3  John C  1922      Prison    3.5
2   3  John C  1923      Prison    3.5
2   3  John C  1924      Prison    3.5
3   4  John D  1922        Comp    6.5
4   5  John E  1922   Awareness    7.0
5   6  John F  1922   First Aid    7.2
6   7  John G  1922  BasketBall    2.5
7   8  John H  1922        Tech    5.4

推荐阅读