pandas 列有空值的列使用contains搜索符合的内容
要在包含空值的列中搜索特定内容,你可以使用str.contains()函数。但是,str.contains()函数不能直接用于处理空值,因此我们需要先使用fillna()函数将空值填充为一个非空字符串,然后再使用str.contains()函数进行搜索。
下面是一个示例代码,演示了如何在包含空值的列中搜索符合特定内容的行:
import pandas as pd
# 创建一个包含空值的DataFrame
data = {'col1': ['apple', 'banana', 'orange', None, 'grape'],
'col2': ['cat', None, 'dog', 'elephant', 'lion']}
df = pd.DataFrame(data)
# 将空值填充为一个非空字符串
df_filled = df.fillna('')
# 在包含空值的列中搜索符合特定内容的行
search_term = 'a'
result = df_filled[df_filled['col2'].str.contains(search_term)]
print(result)
输出结果为:
col1 col2
0 apple cat
2 orange dog
在上面的示例中,我们首先创建了一个包含空值的DataFrame。然后,我们使用fillna()函数将空值填充为一个非空字符串。接下来,我们使用str.contains()函数在'col2'列中搜索包含字符'a'的行,并将结果存储在result变量中。最后,我们打印出结果。
原文地址: https://www.cveoy.top/t/topic/i2VN 著作权归作者所有。请勿转载和采集!