[英]pandas join dataframes based on conditions
我正在嘗試通過交叉聯接來創建職位和員工的所有可能組合。 但是我想在加入他們時添加一個條件。 例如。 參見下面的示例數據框
>>> df_pos
Country Pos_id level
0 India 1 2
1 UK 2 2
2 USA 3 4
3 UAE 4 5
4 India 5 1
5 UK 6 3
>>> df_emp
Country Emp_id level
0 UK 11 3
1 UK 12 4
2 USA 13 4
3 Singapore 14 5
4 India 15 2
我想找到Pos_id
和Emp_id
組合, Pos_id
匹配國家/地區,然后匹配的工作級別應等於或+1/-1
,例如。 我們在UK
有一個職位( pos_id 6
),我們有一個pos_id 6
匹配的雇員( 11
和12
),他們的國家也是UK
,工作level
分別為3
和4
,即所需職位(即工作)的=和+1
3
level
)。 參見下面的示例輸出
output_df
0 Pos_id Emp_id
1 1 15
2 2 11
3 3 13
4 5 15
5 6 11
6 6 12
有沒有簡單的方法可以在python pandas中做到這一點。 任何幫助將不勝感激。
創建交叉聯接的表后,可以根據條件進行過濾:
output_df = pd.merge(df_pos, df_emp, how='outer', on='Country')
condition = (output_df.level_x - output_df.level_y).between(-1, 1)
output_df = df_merged[condition][['Pos_id', 'Emp_id']]
我嘗試了這個:
data1 = pd.DataFrame({"Country":["India","UK","USA","UAE","India","UK"], "Pos_id":[1,2,3,4,5,6], "level": [2,2,4,5,1,3]})
data2 = pd.DataFrame({"Country":["UK", "UK","USA", "Singapore","India"],"Emp_id":[11,12,13,14,15], "level":[3,4,4,5,2]})
def get_df(country,pos_id,min,max):
lev = data1.loc[(data1.Country==country) & (data1.Pos_id==pos_id)]["level"]
data = data2.loc[(data2.Country==country) &(data2["level"].isin(list(range(int(lev)-min,int(lev)+max))))]
return data
print(get_df("UK",6,1,1))
您可以簡單地在“國家/地區”上加入,然后再過濾嗎?
例如,我將級別列重命名為emp_level
和pos_level
,以使其更清晰,然后:
df = df_pos.merge(df_emp, on='Country')
output_df = df.loc[(df['pos_level'] >= df['emp_level'] - 1) & (df['pos_level'] <= df['emp_level'] + 1)]
不是最漂亮的東西,而是產生您想要的東西。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.