我正在尝试将sql代码转换为python,已添加sqlfiddlehere
此链接具有输入和预期输出以及 SQL 代码,如下所示:
select a.id, b.country, a.person, b.num
from tab2 a
left join tab1 b
on a.id=b.id
WHERE
case when b.country = 'Denmark' then 'Swiz'
else b.country
end <> 'Russia';
需求是将上面的内容转换为python,先谢谢了!
看看如何创建表和您提供的代码,您可以这样做:
import pandas as pd
data_tab1 = {
'id': [1, 2, 3, 4, 5],
'country': ['Denmark', 'Rome', 'Russia', 'Georgia', 'Austria'],
'num': [10, 20, 30, 40, 50]
}
data_tab2 = {
'id': [1, 2, 3, 4, 5],
'person': ['p1', 'p2', 'p3', 'p4', 'p5']
}
df_tab1 = pd.DataFrame(data_tab1)
df_tab2 = pd.DataFrame(data_tab2)
merged_df = pd.merge(df_tab2, df_tab1, on='id', how='left')
def case_condition(row):
if row['country'] == 'Denmark':
return 'Swiz'
else:
return row['country']
merged_df['country_case'] = merged_df.apply(case_condition, axis=1)
result_df = merged_df[merged_df['country_case'] != 'Russia']
final_result = result_df[['id', 'country', 'person', 'num']]
print(final_result)
这给了你
id country person num
0 1 Denmark p1 10
1 2 Rome p2 20
3 4 Georgia p4 40
4 5 Austria p5 50