python怎么求交集呢。如果是DataFrame某字段求交集,可以用isin,也可以用merge。isin只会保留一边的交集数据,merge则两边都会保留。当然merge不仅仅是取交集。

如果是对Series求交集intersect1d。这种方式的数据筛选权当做取交集吧。

# coding:UTF-8

import pandas as pd
import numpy as np

df1 = pd.DataFrame({
        "id":range(1,5),
        "age":(18, 24, 32, 20),
        "address":('shanghai', "bejing", "shanghai", "guangzhou")
});

df2 = pd.DataFrame({
        "id":range(10,14),
        "age":(20, 16, 25, 24),
        "address":('shanghai', "bejing", "shanghai", "guangzhou")
});


df3 = pd.merge(df1,df2, how='inner',on="age")

df4 = df1[df1["age"].isin(df2["age"])]

#下边是处理Series
s1 = df1["age"]

s2 = df2["age"]

s3 = np.intersect1d(s1, s2)