![](/img/trans.png)
[英]Pandas: Mapping values between 2 dataframes by matching 2 columns values (composite key) to 1 column and the column labels/index of another dataframe
[英]Finding continuous column values in a DataFrame that are not interrupted by values in another DataFrames columns
我有兩個 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
我想用不中斷的連續 id 但df2
中的 id 填充 DataFrame df1
。
output應該如下:
Out[3]:
id value
1 x
2 Nan
3 x
6 x
7 Nan
8 Nan
9 x
請注意,id 4 和 5 被跳過,因為df2
的 id 4 中斷了此處的連續流。
只需制作一個裝有 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.