[英]Pandas expanding a dataframe length but populate each row incrementally based on column
I'm working with a dataframe that looks like this:我正在使用如下所示的 dataframe:
frame requests
0 0 214388438.0
1 1 194980303.0
2 2 179475934.0
3 3 165196540.0
4 4 154815540.0
5 5 123650671.0
6 6 119089045.0
The thing is I want to add each of the value found on the requests column incrementally.问题是我想逐步添加在请求列中找到的每个值。 Say frame 0 should have the first value, frame 1 should have the previous value and the one that comes after followed by 0. I want the dataframe to look something like this:
假设第 0 帧应该有第一个值,第 1 帧应该有前一个值和后面跟着 0 的值。我希望 dataframe 看起来像这样:
frame requests
0 0 214388438.0
1 0 0
2 0 0
3 0 0
....................
48 1 214388438.0
49 1 194980303.0
50 1 0
....................
.. 2 214388438.0
.. 2 194980303.0
.. 2 179475934.0
.. 2 0
Eventually, on the last value for column frame
all rows would be populated by the value on the requests, no more 0s.最终,在列
frame
的最后一个值上,所有行都将由请求中的值填充,不再是 0。
....................
.. 47 214388438.0
.. 47 194980303.0
.. 47 179475934.0
.. 47 165196540.0
.. 47 154815540.0
.. 47 123650671.0
.....................
Assuming df
as input, you can use numpy to reshape and create a new DataFrame:假设
df
作为输入,您可以使用 numpy 重塑并创建一个新的 DataFrame:
import numpy as np
a = df['requests'].to_numpy()
df2 = (pd
.DataFrame(np.tril(np.tile(a, (len(a), 1))), index=df['frame'])
.stack()
.droplevel(1)
.reset_index(name='requests')
)
NB.注意。 You can also use
df['requests']
directly instead of a
, the conversion to array will be done automatically.您也可以直接使用
df['requests']
而不是a
,到数组的转换将自动完成。
output: output:
frame requests
0 0 214388438.0
1 0 0.0
2 0 0.0
3 0 0.0
4 0 0.0
5 0 0.0
6 0 0.0
7 1 214388438.0
8 1 194980303.0
9 1 0.0
10 1 0.0
11 1 0.0
12 1 0.0
13 1 0.0
14 2 214388438.0
15 2 194980303.0
16 2 179475934.0
17 2 0.0
18 2 0.0
19 2 0.0
20 2 0.0
21 3 214388438.0
22 3 194980303.0
23 3 179475934.0
24 3 165196540.0
25 3 0.0
26 3 0.0
27 3 0.0
28 4 214388438.0
29 4 194980303.0
30 4 179475934.0
31 4 165196540.0
32 4 154815540.0
33 4 0.0
34 4 0.0
35 5 214388438.0
36 5 194980303.0
37 5 179475934.0
38 5 165196540.0
39 5 154815540.0
40 5 123650671.0
41 5 0.0
42 6 214388438.0
43 6 194980303.0
44 6 179475934.0
45 6 165196540.0
46 6 154815540.0
47 6 123650671.0
48 6 119089045.0
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.