在 Pandas 中的多列上查找字符串
Posted
技术标签:
【中文标题】在 Pandas 中的多列上查找字符串【英文标题】:Finding string over multiple columns in Pandas 【发布时间】:2018-04-21 05:27:42 【问题描述】:我试图找出一个字符串是否存在于多个列中。如果字符串存在,我想返回 1,如果它不作为数据框中的新系列,我想返回 0。
搜索论坛后,我知道可以使用 str.contains,但我搜索了 100 多个列,因此一次处理单个系列对我来说效率不高。
如果相关,列中有一些 NA。
示例简化数据框:
d = 'strings_1': ['AA', 'AB', 'AV'], 'strings_2': ['BB', 'BA', 'AG'],
'strings_1': ['AE', 'AC', 'AI'], 'strings_3': ['AA', 'DD', 'PP'],
'strings_4': ['AV', 'AB', 'BV']
simple_df = pd.DataFrame(data=d)
例如,如果我有兴趣查找“AA”,我想返回以下数据框。
示例目标数据框:
d = 'strings_1': ['AA', 'AB', 'AV'], 'strings_2': ['BB', 'BA', 'AG'],
'strings_1': ['AE', 'AC', 'AI'], 'strings_3': ['AA', 'DD', 'PP'],
'strings_4': ['AV', 'AB', 'BV'], 'AA_TRUE': [1, 0, 0]
target_df = pd.DataFrame(data=d)
非常感谢您的帮助。
【问题讨论】:
你有字符串列表吗?你说 `1 如果字符串存在`哪个字符串? 在我的示例中它是 AA,但是是的,会有一个我感兴趣的列表。我可能会单独分配它们,因为我想要多个标签。 下次也将其添加到问题中。我们怎么能猜到你有一个包含 ['AA'] 的列表? 谢谢会做(在例子中不是很明显吗?) 【参考方案1】:如果需要检查混合值 - 数字与字符串比较由 values
创建的 numpy 数组,请使用 DataFrame.any
每行检查至少一个 True
并最后转换为 int
:
simple_df['new'] = (simple_df.values == 'AA').any(1).astype(int)
#or cast all values to string before comparing
#simple_df['new'] = (simple_df.astype(str)== 'AA').any(1).astype(int)
print (simple_df)
strings_1 strings_2 strings_3 strings_4 new
0 AE BB AA AV 1
1 AC BA DD AB 0
2 AI AG PP BV 0
详情:
print ((simple_df.values == 'AA'))
[[False False True False False]
[False False False False False]
[False False False False False]]
print ((simple_df.values == 'AA').any(1))
[ True False False]
如果需要检查子串:
simple_df['new'] = simple_df.applymap(lambda x: 'G' in x).any(1).astype(int)
print (simple_df)
strings_1 strings_2 strings_3 strings_4 new
0 AE BB AA AV 0
1 AC BA DD AB 0
2 AI AG PP BV 1
【讨论】:
how to use two substrings at a time in entire data. like here using G ,can use E and G at a time ?
simple_df.applymap(lambda x: 'G|E' in x).any(1).astype(int)
我这样写但它没有给出输出
@dondapati - 需要simple_df.applymap(lambda x: any(y in x for y in ['G','E']))
can we apply the above function with selected columns ? just apply the 1 and 2 columns
@dondapati - 当然,使用simple_df.iloc[:, :1].applymap(lambda x: any(y in x for y in ['G','E']))
以上是关于在 Pandas 中的多列上查找字符串的主要内容,如果未能解决你的问题,请参考以下文章
Pandas:在多列中查找具有匹配值的行的 Pythonic 方法(分层条件)
Pandas使用split函数基于指定分隔符拆分数据列的内容为列表设置expand参数将拆分结果列表内容转化为多列数据并添加到原数据中replace函数基于正则表达式替换字符串数据列中的匹配内容