【问题标题】:Add the string from one dataframe in a new column of a second dataframe while comparing values在比较值时将来自一个数据帧的字符串添加到第二个数据帧的新列中
【发布时间】:2021-03-19 20:18:11
【问题描述】:

我想检查一个数据框中的列中的值是否存在于第二个数据框的列中。如果存在,则将该值添加到第二个数据帧中同一行的新列中。所有值都是字符串值。两个数据框的大小都不同。第二个数据框也有大约 70 万条记录。所以我拥有的数据框:

DF1

THINGS
book+pen
CAR 
chair
laptop

DF2

Description
I want a new book.
I will pen down this things 
A quick ride in my new car.
Cars are awesome.
My laptop's memory is bad.
Maybe try sitting on that CHAIR.

我想要的输出是添加一个“更新”列:

Description                        Updated
I want a new book.                 book
I will pen down this things        pen
A quick ride in my new car.        car
Cars are awesome.                  car
My laptop's memory is bad.         laptop
Maybe try sitting on that CHAIR.   chair
Search for that book in my laptop. book+laptop

我已经尝试过暴力方法,但处理时间太长。提前致谢!

【问题讨论】:

  • 如果你有范围索引,你可以只在索引上合并,如果没有,你可以df.reset_index()df2.reset_index() 然后只是pd.merge(df, df2, left_index=True, right_index=True) 也可以了解更多关于stackoverflow.com/questions/40468069/…的信息

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


【解决方案1】:

请试试这个。

  1. 使用 str.splitexplode 首先从 df1 获取要匹配的字符串列表
  2. 为不区分大小写的匹配创建了两个全小写的列。
  3. 使用str.findall检索dfs之间的匹配字符串。
  4. 使用str.strip 去掉括号和引号

代码:

df1 = df1.assign(THINGS=df1['THINGS'].str.split('+')).explode('THINGS')
df1['THINGS2'] = df1.THINGS.str.lower()
df2['Description2'] =  df2.Description.str.lower()
df2['Updated'] = df2.Description2.str.findall('|'.join(df1.THINGS2))
df2['Updated'] = df2.Updated.astype(str).str.strip(to_strip=r'''[|]|\'''')
del df2['Description2']
print(df2)

打印:

                        Description Updated
0                I want a new book.    book
1      I will pen down this things      pen
2       A quick ride in my new car.     car
3                 Cars are awesome.     car
4           My laptops hangs a lot.  laptop
5  Maybe try sitting on that CHAIR.   chair

【讨论】:

  • @yellow_smile 有帮助吗?
  • 不只是从此代码中获取空字符串:df2['Updated'] = df2.Description2.str.findall('|'.join(df1.THINGS2))
  • 嗯.. 你是在你提供的数据集上测试它吗? “更新”列的所有行都是空白的吗?我刚刚测试过,它又能正常工作了!。
  • 是的,相同的数据,是的,所有行都是空白的,为什么
  • 很奇怪..我刚刚复制了您粘贴的数据集..explode 工作正常吗?你试过打印 df1 吗?
猜你喜欢
  • 1970-01-01
  • 2023-04-01
  • 2019-06-23
  • 1970-01-01
  • 1970-01-01
  • 2020-08-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多