pandas 两行索引之间的填充值(行只能按值查找)
pandas fill value between the index of two rows(rows only find by a value)
我有一个系列df
:
index
0 1
1 1
2 1
3 1
4 1
5 -1
6 -1
7 -1
8 1
9 1
10 1
11 -1
dtype: int64
另一个boolean
系列是点赞指标或点数b
:
index
0 False
1 False
2 True
3 False
4 False
5 False
6 True
7 False
8 False
9 True
10 False
11 False
我可以使用 b
、df[b]=0
:
设置 df
值
index
0 1
1 1
2 0
3 1
4 1
5 -1
6 0
7 -1
8 1
9 0
10 1
11 -1
现在我想用值 -1
填充 2:5
、6:7
、9:11
之间的值,我想要的结果是一个新的 df
:
index
0 1
1 1
2 -1
3 -1
4 -1
5 -1
6 -1
7 -1
8 1
9 -1
10 -1
11 -1
也就是说当b
是True
时,(index:2,6,9),我会在df
之间的index( index:2,6,9) 和最近的 -1
值的索引 (index:5,7,11).
填充值为-1
,填充范围为[2:5,6:7,9:11]
我想过where
、replace
、pad
等方法,但无法解决。也许找到它的索引数组[2,6,9]
,和最近的-1
数组[5,7,11]
,重新排列成[2:5,6:7,9:11]
是一种方法。
有没有比较有用的方法?
numpy.where()
看起来它可以满足您的需求:
代码:
import numpy as np
starts = np.where(df == 0)
ends = np.where(df == -1)
for start, end in zip(starts[0], ends[0]):
df[start:end] = -1
测试数据:
import pandas as pd
df = pd.DataFrame([1, 1, 1, 1, 1, -1, -1, -1, 1, 1, 1, -1])
b = pd.DataFrame([False, False, True, False, False, False, True,
False, False, True, False, False,])
df[b] = 0
print(df)
结果:
0
0 1
1 1
2 -1
3 -1
4 -1
5 -1
6 -1
7 -1
8 1
9 -1
10 -1
11 -1
我有一个系列df
:
index
0 1
1 1
2 1
3 1
4 1
5 -1
6 -1
7 -1
8 1
9 1
10 1
11 -1
dtype: int64
另一个boolean
系列是点赞指标或点数b
:
index
0 False
1 False
2 True
3 False
4 False
5 False
6 True
7 False
8 False
9 True
10 False
11 False
我可以使用 b
、df[b]=0
:
df
值
index
0 1
1 1
2 0
3 1
4 1
5 -1
6 0
7 -1
8 1
9 0
10 1
11 -1
现在我想用值 -1
填充 2:5
、6:7
、9:11
之间的值,我想要的结果是一个新的 df
:
index
0 1
1 1
2 -1
3 -1
4 -1
5 -1
6 -1
7 -1
8 1
9 -1
10 -1
11 -1
也就是说当b
是True
时,(index:2,6,9),我会在df
之间的index( index:2,6,9) 和最近的 -1
值的索引 (index:5,7,11).
填充值为-1
,填充范围为[2:5,6:7,9:11]
我想过where
、replace
、pad
等方法,但无法解决。也许找到它的索引数组[2,6,9]
,和最近的-1
数组[5,7,11]
,重新排列成[2:5,6:7,9:11]
是一种方法。
有没有比较有用的方法?
numpy.where()
看起来它可以满足您的需求:
代码:
import numpy as np
starts = np.where(df == 0)
ends = np.where(df == -1)
for start, end in zip(starts[0], ends[0]):
df[start:end] = -1
测试数据:
import pandas as pd
df = pd.DataFrame([1, 1, 1, 1, 1, -1, -1, -1, 1, 1, 1, -1])
b = pd.DataFrame([False, False, True, False, False, False, True,
False, False, True, False, False,])
df[b] = 0
print(df)
结果:
0
0 1
1 1
2 -1
3 -1
4 -1
5 -1
6 -1
7 -1
8 1
9 -1
10 -1
11 -1