【发布时间】:2021-07-05 19:39:15
【问题描述】:
这是板球得分的示例 csv 文件:
>>> df
venue ball run extra wide noball
0 a 0.1 0 1 NaN NaN
1 a 0.2 4 0 NaN NaN
2 a 0.3 1 5 5.0 NaN
3 a 0.4 1 0 NaN NaN
4 a 0.5 1 1 NaN 1.0
5 a 0.6 2 1 NaN NaN
6 a 0.7 6 2 1.0 1.0
7 a 0.8 0 0 NaN NaN
8 a 0.9 1 1 NaN NaN
9 a 1.1 2 2 NaN NaN
10 a 1.2 1 0 NaN NaN
11 a 1.3 6 1 NaN NaN
12 a 1.4 0 2 NaN 2.0
13 a 1.5 1 0 NaN NaN
14 a 1.6 2 0 NaN NaN
15 a 1.7 0 1 NaN NaN
16 a 0.1 0 5 NaN NaN
17 a 0.2 4 0 NaN NaN
18 a 0.3 1 1 NaN NaN
19 a 0.4 3 0 NaN NaN
20 a 0.5 0 0 NaN NaN
21 a 0.6 0 2 2.0 NaN
22 a 0.7 6 1 NaN NaN
23 a 1.1 4 0 NaN NaN
我想从这个数据框中更新球值,生成 2 个新列并删除 4 个整列。条件是
- 当“wide”或“noball”为空时,crun = crun + run + extra until ball = 0.1(递归)
- 当“wide”或“noball”不为null时,并发ball值不会增加,在crun计算后将被丢弃。 crun = crun + run + 额外。它将一直持续到 ball = 0.1(递归),例如。让我细分一下:从行索引 0 到 8:| 0.1 "wide" 或 "noball" 为 null 并且 crun = 1 | 0.2 "wide" 或 "noball" 为空并且 crun = 1+4 =5| 0.3 "wide" 或 "noball" 不为空(已删除) | 0.4 "wide" 或 "noball" 为空(变为 0.3)并且 crun = 5+1+5+1 = 12| 0.5 "wide" 或 "noball" 不为空(已删除) | 0.6 "wide" 或 "noball" 为空(变为 0.4)并且 crun = 12+1+1+2+1 =17| 0.7 "wide" 或 "noball" 不为空(已删除) | 0.8 "wide" 或 "noball" 为空(变为 0.5)并且 crun = 17+6+2 = 25| 0.9 "wide" 或 "noball" 为空(变为 0.6)并且 crun = 25+1+1 =27|
- 最后将创建“total”列,它返回 crun 的最大值,直到 ball = 0.1(递归)。然后应该删除“run”、“extra”、“wide”、“noball”列。
我想要的输出:
venue ball crun total
0 a 0.1 1 45
1 a 0.2 5 45
2 a 0.3 12 45
3 a 0.4 17 45
4 a 0.5 25 45
5 a 0.6 27 45
6 a 1.1 31 45
7 a 1.2 32 45
8 a 1.3 39 45
9 a 1.4 42 45
10 a 1.5 44 45
11 a 1.6 45 45
12 a 0.1 5 27
13 a 0.2 9 27
14 a 0.3 11 27
15 a 0.4 14 27
16 a 0.5 14 27
17 a 0.6 23 27
18 a 1.1 27 27
我觉得太复杂了,请帮忙。我试过的代码:
df = pd.read_csv("data.csv")
gr = df.groupby(df.ball.eq(0.1).cumsum())
df["crun"] = gr.runs.cumsum()
df["total"] = gr.current_run.transform("max")
df = df.drop(['run', 'extra', 'wide', 'noball'], axis=1)
【问题讨论】:
-
在您的结果数据帧行索引 5-6 中,列球中的值如何从 0.6 变为 1.1 有点不清楚?你能解释一下吗
-
让我细分一下:从行索引 0 到 8:| 0.1 "wide" 或 "noball" 为 null 并且 crun = 1 | 0.2 "wide" 或 "noball" 为空并且 crun = 1+4 =5| 0.3 "wide" 或 "noball" 不为空(已删除) | 0.4 "wide" 或 "noball" 为空(变为 0.3)并且 crun = 5+1+5+1 = 12| 0.5 "wide" 或 "noball" 不为空(已删除) | 0.6 "wide" 或 "noball" 为空(变为 0.4)并且 crun = 12+1+1+2+1 =17| 0.7 "wide" 或 "noball" 不为空(已删除) | 0.8 "wide" 或 "noball" 为空(变为 0.5)并且 crun = 17+6+2 = 25| 0.9 "wide" 或 "noball" 为空(变为 0.6)并且 crun = 25+1+1 =27| @Ben.T
标签: python pandas dataframe csv