我正在嘗試根據另一個資料框中的值在資料框中創建一個新列。
df1 是,
Name Depth
A 100
A 120
B 200
df2 是,
Name Start_Depth End_Depth Zone
A 50 150 Zone1
A 150 200 Zone2
B 50 120 Zone3
B 120 300 Zone4
我想在 df1 中添加 Zone 列,基于兩個條件,
- “名稱”應在兩個資料框中匹配
- 對于相同的“名稱”,df1.Depth 應該在 df2 中的 Start_Depth 和 End_Depth 之間
輸出 df1,
Name Depth Zone
A 100 Zone1
A 120 Zone1
B 200 Zone4
uj5u.com熱心網友回復:
使用df.merge有df.query:
In [120]: r = df1.merge(df2).query('End_Depth >= Depth > Start_Depth')[['Name', 'Depth', 'Zone']]
In [121]: r
Out[121]:
Name Depth Zone
0 A 100 Zone1
2 A 120 Zone1
5 B 200 Zone4
或使用Series.between:
In [114]: x = df1.merge(df2)
In [124]: r = x[x.Depth.between(x.Start_Depth, x.End_Depth)][['Name', 'Depth', 'Zone']]
In [125]: r
Out[125]:
Name Depth Zone
0 A 100 Zone1
2 A 120 Zone1
5 B 200 Zone4
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/397685.html
