小编ali*_*naz的帖子

如何从数据框列中提取与列表的精确匹配?

我有一个包含文本的大型数据框,我想用它从单词列表(其中大约有 1k 个单词)中查找匹配项。

我已经设法从数据框中的列表中获取该单词的缺失/存在,但对我来说知道哪个单词匹配也很重要。有时与列表中的多个单词完全匹配,我希望将它们全部匹配。

我尝试使用下面的代码,但它给了我部分匹配 - 音节而不是完整的单词。

#this is a code to recreate the initial DF

import pandas as pd

df_data= [['orange','0'],
['apple and lemon','1'],
['lemon and orange','1']]

df= pd.DataFrame(df_data,columns=['text','match','exact word'])
Run Code Online (Sandbox Code Playgroud)

初始DF:

 text                 match
 orange               0
 apple and lemon      1
 lemon and orange     1
Run Code Online (Sandbox Code Playgroud)

这是我需要匹配的单词列表

 exactmatch = ['apple', 'lemon']
Run Code Online (Sandbox Code Playgroud)

预期结果:

 text                    match  exact words
 orange                    0         0 
 apple and lemon           1        'apple','lemon'
 lemon and orange          1        'lemon'
Run Code Online (Sandbox Code Playgroud)

这是我尝试过的:

# for some rows it gives me words I want, 
#and for …
Run Code Online (Sandbox Code Playgroud)

python regex dataframe pandas

1
推荐指数
1
解决办法
4580
查看次数

将嵌套字典转换为 Pandas 数据框

我有一本看起来像这样的字典:

{'136454': [{'city': 'Kabul', 'country': 'AF'}],
 '137824': [{'city': 'Kabul', 'country': 'AF'}],
 '134134': [{'city': 'Kabul', 'country': 'AF'}],
 '138322': [{'city': 'Fujairah', 'country': 'AE'},
  {'city': 'Kabul', 'country': 'AF'}],
 '137246': [{'city': 'Fujairah', 'country': 'AE'},
  {'city': 'Kabul', 'country': 'AF'}, {'city': 'New Delhi', 'country': 'IN'],
 '133141': [{'city': 'Kabul', 'country': 'AF'}]}
Run Code Online (Sandbox Code Playgroud)

我想要的是一个看起来像这样的数据框:

'136454' | 'Kabul'|'AF'
'137824' | 'Kabul'|'AF'
'134134' | 'Kabul'|'AF'
'138322' |'Fujairah'| 'AE'
'138322'  | 'Kabul'| 'AF'
'137246' | 'Fujairah'| 'AE'
'137246' | 'Kabul' | 'AE'
'137246' | 'New Delhi'| 'IN'
'133141'| 'Kabul'| 'AF'
Run Code Online (Sandbox Code Playgroud)

我目前得到的只是每个键的第一个值。不太擅长熊猫,所以有点困惑。

python dictionary pandas

0
推荐指数
1
解决办法
66
查看次数

标签 统计

pandas ×2

python ×2

dataframe ×1

dictionary ×1

regex ×1