我想在熊猫中实现以下 sql 等效值 -
SELECT
A.col1,
A.col2,
A.col3,
A.col4,
A.col5
FROM Table1 A
INNER JOIN Table1 b
ON A.col1 = B.col1 AND
A.col2 = B.col2
WHERE
(A.col3 <> 0) AND
(A.col4 <> B.col4)
我能够实现的大熊猫部分是——
#Dataframe dfTable1All contains the columns col1, col2, col3, col4, col5
#Dataframe dfTable1 contains the columns col1, col2, col4
dfTable1All = dfTable1All [(dfTable1All ['col3'] <> 0)]
dfjoin = pd.merge(dfTable1All, dfTable1, on=('col1','col2'), how='inner')
你能帮我如何在内部连接中使用where条件吗?
WHERE (A.col4 <> B.col4)
谢谢。
如果您查看merge
文档字符串,则可以选择在具有相同名称的列上使用后缀。 默认值为 '_x'
和 '_y'
。 因此,要过滤两个 col4 不相等的地方,您可以执行以下操作:
dfjoin = dfjoin[dfjoin['col4_x'] != dfjoin['col4_y']]
我会把它分解成单独的操作
dfA.set_index(['col1', 'col2'], inplace=True)
dfB.set_index(['col1', 'col2'], inplace=True)
dfAB = dfA.join(dfB, rsuffix='_A', lsuffix='_B')
dfAB.query("col3_A != 0 and col4_A != col4_B")