python - 使用来自 pandas 中其他两列的匹配项的值创建新列

标签 python pandas

下面是我拥有的 pandas data frame 的一个子集

           index             name_matches dist_matches
38  PO1000000345                  M-00346      M-00346
39  PO1000000352                               M-00804
40  PO1000000354                  M-00196      M-00196
41  PO1000000355                  M-00514      M-00514
42  PO1000000382          M-00353,M-00354      M-00354
43  PO1000000411                                      
44  PO1000000451                                      
45  PO1000000512                               M-00680
46  PO1000000530                  M-00089             
47  PO1000000531                  M-00087      M-00087
48  PO1000000553  M-00917,M-00920,M-00922      M-00920

我正在尝试获取一个新列 (comb_matches),它提取 name_matchesdist_matches 列中的匹配值。有时,列中会有一个或多个值以逗号分隔。下面显示了我希望获得的输出示例。

           index             name_matches dist_matches  comb_matches
38  PO1000000345                  M-00346      M-00346       M-00346
39  PO1000000352                               M-00804
40  PO1000000354                  M-00196      M-00196       M-00196
41  PO1000000355                  M-00514      M-00514       M-00514
42  PO1000000382          M-00353,M-00354      M-00354       M-00354
43  PO1000000411                                      
44  PO1000000451                                      
45  PO1000000512                               M-00680
46  PO1000000530                  M-00089             
47  PO1000000531                  M-00087      M-00087       M-00087
48  PO1000000553  M-00917,M-00920,M-00922      M-00920       M-00920

有什么简单的方法可以得到上面的内容吗?

最佳答案

没有简单的方法。 Pandas 不是为这种任务而设计的,它不是可矢量化的。您最好的选择可能是列表理解:

s1 = df['dist_matches'].astype(str)
s2 = df['name_matches'].astype(str).str.split(',')
mask = [i in j for i, j in zip(s1, s2)]

df['comb_match'] = np.where(mask, df['dist_matches'], np.nan)

性能基准测试

为了证明 Pandas str 方法不是真正矢量化的事实:

# Python 3.6.5, Pandas 0.23.0

def wen(df):
    Bool = df.name_matches.str.split(',',expand=True).isin(df.dist_matches).any(1)    
    df['comb_match'] = np.where(Bool, df.dist_matches, '')
    return df

def jpp(df):
    s1 = df['dist_matches'].astype(str)
    s2 = df['name_matches'].astype(str).str.split(',')
    mask = [i in j for i, j in zip(s1, s2)]
    df['comb_match'] = np.where(mask, df['dist_matches'], np.nan)
    return df

df = pd.concat([df]*1000, ignore_index=True)

assert jpp(df).equals(wen(df))

%timeit jpp(df)  # 12.2 ms
%timeit wen(df)  # 32.7 ms

关于python - 使用来自 pandas 中其他两列的匹配项的值创建新列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53050791/

相关文章:

python - Pandas :减去两个日期列,结果是一个整数

python - 通过第三个表排除多对多关系

python - pytesseract.image_to_string 似乎无法从图像中提取文本

python - 使用 Django 部署 Google Analytics

python - 将 DataFrame Pandas 中第二行的列分类到第一行?

Python Pandas - loc 创建 fortran 有序 numpy 数组

python - Python itertools groupby 中令人不安的奇怪行为/错误?

python - 将 for 循环转换为字典理解

python - 根据条件合并 Dataframe 行

python - 我有一个带有两个独立离散变量的高斯函数。如何创建所有可能值的矩阵?