本文介绍了 pandas :为系列中的每个字符串值返回所有匹配的键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何以逗号分隔值的形式返回搜索列表中所有匹配的键.

How to return all the matched keys of from a search list as comma-separated values.

例如

s = pd.Series(['cat dog','hat cat','dog','fog cat','pet'])
searchfor = ['cat', 'dog']

我想得到这个:

['猫,狗','猫','狗','猫','无']

推荐答案

我的同事帮我解决了这个问题.这是我最终做到的:

My colleague helped me with it.Here is how I finally did it:

s = pandas.Series(['cat dog','hat cat','dog','fog cat','pet'])
searchfor = ['cat', 'dog']

b = ['']*len(s)
for i in numpy.arange(0,len(s)):
    for j in numpy.arange(0,len(searchfor)):
        b[i] = b[i] + ', ' + searchfor[j] if searchfor[j] in s[i] and b[i]!= '' else (searchfor[j] if searchfor[j] in s[i] else b[i])
df = DataFrame({'s': s, 'searchfor': [numpy.nan if i=='' else i for i in b]})

df

    s        searchfor
0   cat dog  cat, dog
1   hat cat  cat
2   dog      dog
3   fog cat  cat
4   pet      NaN

这篇关于 pandas :为系列中的每个字符串值返回所有匹配的键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-24 15:14