有什么有效的方法可以在python中编写此代码

时间:2020-05-07 15:45:19

标签: python python-3.x pandas list numpy

我想用python编写这段代码。

proc sql;
select count(distinct ID_1)
from DATA
where ID_1 = ID_2 and ID_type in ("11","23","46");
quit;

我可以分三个步骤完成

a = [x if x==y and z in ("11","23", "46") for x,y,z in zip(DATA['x'],DATA['y'],DATA['z'])]
a = [i for i in a if str(i) != 'nan']
len(np.unique(a))

有什么有效的方法可以编写相同的代码。

1 个答案:

答案 0 :(得分:4)

大多数常见的SQL操作都可以在python和pandas中轻松转换:

DATA[(DATA.ID_1 == DATA.ID_2) & (DATA.ID_type.isin(["11", "23", "46"]))].ID_1.nunique()

阅读introduction to pandas,了解更多信息。