[英]Finding continuous column values in a DataFrame that are not interrupted by values in another DataFrames columns
I have two DataFrames as follows:我有两个 DataFrame,如下所示:
df1 = pd.DataFrame({
'id': [1, 3, 6, 9],
'value' : ['x']*4})
Out[1]:
id value
1 x
3 x
6 x
9 x
df2 = pd.DataFrame({
'id': [4, 10, 12],
'value': ['x']*3})
Out[2]:
id value
4 x
10 x
12 x
I want to fill DataFrame df1
with continuous ids that are not interrupted but the ids in df2
.我想用不中断的连续 id 但df2
中的 id 填充 DataFrame df1
。
The output should be as follows: output应该如下:
Out[3]:
id value
1 x
2 Nan
3 x
6 x
7 Nan
8 Nan
9 x
Note that id 4 and 5 are skipped because df2
have id 4 that interrupt the continuous flow here.请注意,id 4 和 5 被跳过,因为df2
的 id 4 中断了此处的连续流。
Just make a loop holding a boolean, maybe not as fast as you want but it does the trick只需制作一个装有 boolean 的循环,可能没有你想要的那么快,但它可以解决问题
a = [1,3,6,9]
b = [4,10,12]
add_id = True
result = []
for i in range(a[0], a[-1] + 1):
if i in a:
add_id = True
if i in b:
add_id = False
if add_id:
result.append(i)
output: [1, 2, 3, 6, 7, 8, 9]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.