栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何在字符串包含上合并pandas?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何在字符串包含上合并pandas?

新答案

这是一种基于pandas / numpy的方法。

rhs = (df1.column_common          .apply(lambda x: df2[df2.column_common.str.find(x).ge(0)]['column_b'])          .bfill(axis=1)          .iloc[:, 0])(pd.concat([df1.column_a, rhs], axis=1, ignore_index=True) .rename(columns={0: 'column_a', 1: 'column_b'}))  column_a column_b0     John    Moore1  Michael    Cohen2      Dan    Smith3   George      NaN4     Adam    Faber

旧答案

这是左联接行为的一种解决方案,因为它不会保留

column_a
不匹配任何
column_b
值的值。这比上面的numpy /
pandas解决方案要慢,因为它使用两个嵌套
iterrows
循环来构建python列表。

tups = [(a1, a2) for i, (a1, b1) in df1.iterrows()       for j, (a2, b2) in df2.iterrows()        if b1 in b2](pd.Dataframe(tups, columns=['column_a', 'column_b'])   .drop_duplicates('column_a')   .reset_index(drop=True))  column_a column_b0     John    Moore1  Michael    Cohen2      Dan    Smith3     Adam    Faber


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/633963.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号