我使用以下代码创建了一个 pandas 数据框:
ds = {"col1":[1,1,1,1,2,3,4,4,4,4,4,5,4,4,5,6]}
df = pd.DataFrame(data=ds)
数据框看起来像这样:
print(df)
col1
0 1
1 1
2 1
3 1
4 2
5 3
6 4
7 4
8 4
9 4
10 4
11 5
12 4
13 4
14 5
15 6
我需要计算一个新的数据框列(称为
col2
),其中包含来自col1
的next值,该值不同于当前值。
例子。
让我们看一下第 0 行。
col1
中的值为 1。
col1
中下一个不同于 1 的值是什么?它是值 2(在row 4
)。
现在让我们看一下第 1 行。 col1 中的值为 1。
col1
中下一个不同于 1 的值是什么?它是值 2(在row 4
)。
等等
生成的数据框如下所示:
生成这种数据框的 python 代码是什么?
where
、shift
的掩码,以及 bfill
:
# identify the first value of each stretch
m = df['col1'].ne(df['col1'].shift())
# mask the other, shift up, backfill
df['col2'] = df['col1'].where(m).shift(-1).bfill()
输出:
col1 col2
0 1 2.0
1 1 2.0
2 1 2.0
3 1 2.0
4 2 3.0
5 3 4.0
6 4 5.0
7 4 5.0
8 4 5.0
9 4 5.0
10 4 5.0
11 5 4.0
12 4 5.0
13 4 5.0
14 5 6.0
15 6 NaN
中级理解逻辑;
col1 col2 m where(m) shift(-1)
0 1 2.0 True 1.0 NaN
1 1 2.0 False NaN NaN
2 1 2.0 False NaN NaN
3 1 2.0 False NaN 2.0
4 2 3.0 True 2.0 3.0
5 3 4.0 True 3.0 4.0
6 4 5.0 True 4.0 NaN
7 4 5.0 False NaN NaN
8 4 5.0 False NaN NaN
9 4 5.0 False NaN NaN
10 4 5.0 False NaN 5.0
11 5 4.0 True 5.0 4.0
12 4 5.0 True 4.0 NaN
13 4 5.0 False NaN 5.0
14 5 6.0 True 5.0 6.0
15 6 NaN True 6.0 NaN
这是另一个解决方案:
s = df['col1'].diff().ne(0).cumsum()
s.map(df.groupby(s)['col1'].first().shift(-1))
输出:
0 2.0
1 2.0
2 2.0
3 2.0
4 3.0
5 4.0
6 5.0
7 5.0
8 5.0
9 5.0
10 5.0
11 4.0
12 5.0
13 5.0
14 6.0
15 NaN