python - 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
解决方案
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
推荐阅读
- vbscript - 从注册表中删除程序
- javascript - chart.js - 如何将图形线延伸到画布边缘(图片)
- python - 如何获取 SOM(Self Organizing Maps)中的重要特征?
- python - 在函数中使用可选参数来反转范围 python 3
- node.js - Express Route 的高阶函数
- python - 网页抓取:使用 python 从 html 中的 xpath 中提取 url:airbnb 列表
- soapui - 在 SOAP UI 中测试多个请求?
- java - 查询具有字段组合和 in 语句的行
- spring - ConditionalOnProperties 不会在具有多个端点的类中切换端点 Spring Boot
- r - 给定一列键,用基于字典的一列字符串覆盖它