使用 while 获取下一个非空值
Using while to grab the next not null value
我在 Python 中有这个 Pandas 数据框,它列出了球队在一场足球比赛中所做的所有动作。如果比赛有得分,我会在“得分”栏中获得得分,否则此栏为空:
play_id
得分
1
2
3
4
6
5
1
6
7
8
3
9
10
我想根据这些条件创建一个名为“next_score”的新列:
- 如果比赛有积分,我要抢分
- 如果比赛没有得分(即值为空),我想抓住下一个得分。
table 看起来像这样:
play_id
得分
next_score
1
6
2
6
3
6
4
6
6
5
1
1
6
3
7
3
8
3
3
9
6
10
6
6
我一直在使用这个代码:
next_score = []
for point in df['Score']:
if point == "":
while point+1 == "":
continue
else:
next_score.append(point)
break
else:
next_score.append(point)
df['next_score'] = next_score
但这给了我与“分数”列相同的结果。我无法告诉我的代码获取下一个评分结果。谁能帮我解决这个问题?
Pandas 随附电池:
df['next_score'] = df['Score'].fillna(method='backfill')
我在 Python 中有这个 Pandas 数据框,它列出了球队在一场足球比赛中所做的所有动作。如果比赛有得分,我会在“得分”栏中获得得分,否则此栏为空:
play_id | 得分 |
---|---|
1 | |
2 | |
3 | |
4 | 6 |
5 | 1 |
6 | |
7 | |
8 | 3 |
9 | |
10 |
我想根据这些条件创建一个名为“next_score”的新列:
- 如果比赛有积分,我要抢分
- 如果比赛没有得分(即值为空),我想抓住下一个得分。
table 看起来像这样:
play_id | 得分 | next_score |
---|---|---|
1 | 6 | |
2 | 6 | |
3 | 6 | |
4 | 6 | 6 |
5 | 1 | 1 |
6 | 3 | |
7 | 3 | |
8 | 3 | 3 |
9 | 6 | |
10 | 6 | 6 |
我一直在使用这个代码:
next_score = []
for point in df['Score']:
if point == "":
while point+1 == "":
continue
else:
next_score.append(point)
break
else:
next_score.append(point)
df['next_score'] = next_score
但这给了我与“分数”列相同的结果。我无法告诉我的代码获取下一个评分结果。谁能帮我解决这个问题?
Pandas 随附电池:
df['next_score'] = df['Score'].fillna(method='backfill')