简体   繁体   English

"检查字符串是否在熊猫数据框中"

[英]Check if string is in a pandas dataframe

I would like to see if a particular string exists in a particular column within my dataframe.我想看看我的数据框中的特定列中是否存在特定字符串。

I'm getting the error我收到错误

ValueError: The truth value of a Series is ambiguous. ValueError:Series 的真值不明确。 Use a.empty, a.bool(), a.item(), a.any() or a.all().使用 a.empty、a.bool()、a.item()、a.any() 或 a.all()。

<\/blockquote>

 import pandas as pd BabyDataSet = [('Bob', 968), ('Jessica', 155), ('Mary', 77), ('John', 578), ('Mel', 973)] a = pd.DataFrame(data=BabyDataSet, columns=['Names', 'Births']) if a['Names'].str.contains('Mel'): print ("Mel is there")<\/code><\/pre>"

a['Names'].str.contains('Mel') will return an indicator vector of boolean values of size len(BabyDataSet) a['Names'].str.contains('Mel')将返回大小为len(BabyDataSet)的布尔值的指示向量

Therefore, you can use因此,您可以使用

mel_count=a['Names'].str.contains('Mel').sum()
if mel_count>0:
    print ("There are {m} Mels".format(m=mel_count))

Or any() , if you don't care how many records match your query或者any() ,如果你不关心有多少记录匹配你的查询

if a['Names'].str.contains('Mel').any():
    print ("Mel is there")

You should use any()你应该使用any()

In [98]: a['Names'].str.contains('Mel').any()
Out[98]: True

In [99]: if a['Names'].str.contains('Mel').any():
   ....:     print "Mel is there"
   ....:
Mel is there

a['Names'].str.contains('Mel') gives you a series of bool values a['Names'].str.contains('Mel')为您提供一系列布尔值

In [100]: a['Names'].str.contains('Mel')
Out[100]:
0    False
1    False
2    False
3    False
4     True
Name: Names, dtype: bool

OP meant to find out whether the string 'Mel' exists in a particular column, not contained in any string in the column. OP 旨在找出字符串 'Mel' 是否存在于特定列中,而不包含在该列中的任何字符串中。 Therefore the use of contains is not needed, and is not efficient.因此,不需要使用contains ,而且效率不高。

A simple equals-to is enough:一个简单的等于就足够了:

df = pd.DataFrame({"names": ["Melvin", "Mel", "Me", "Mel", "A.Mel"]})

mel_count = (df['names'] == 'Mel').sum() 
print("There are {num} instances of 'Mel'. ".format(num=mel_count)) 
 
mel_exists = (df['names'] == 'Mel').any() 
print("'Mel' exists in the dataframe.".format(num=mel_exists)) 

mel_exists2 = 'Mel' in df['names'].values 
print("'Mel' is in the dataframe: " + str(mel_exists2)) 

Prints:印刷:

There are 2 instances of 'Mel'. 
'Mel' exists in the dataframe.
'Mel' is in the dataframe: True

I bumped into the same problem, I used:我遇到了同样的问题,我用过:

if "Mel" in a["Names"].values:
    print("Yep")

But this solution may be slower since internally pandas create a list from a Series.但是这个解决方案可能会更慢,因为熊猫在内部创建了一个系列的列表。

If there is any chance that you will need to search for empty strings,如果您有可能需要搜索空字符串,

    a['Names'].str.contains('') 

will NOT work, as it will always return True.将不起作用,因为它总是返回 True。

Instead, use相反,使用

    if '' in a["Names"].values

to accurately reflect whether or not a string is in a Series, including the edge case of searching for an empty string.准确反映字符串是否在系列中,包括搜索空字符串的边缘情况。

Pandas seem to be recommending df.to_numpy since the other methods still raise a FutureWarning : https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_numpy.html#pandas.DataFrame.to_numpy熊猫似乎在推荐df.to_numpy since其他方法仍然会引发FutureWarninghttps : FutureWarning

So, an alternative that would work int this case is:因此,在这种情况下可以使用的替代方法是:

b=a['Names']
c = b.to_numpy().tolist()
if 'Mel' in c:
     print("Mel is in the dataframe column Names")

用于不区分大小写的搜索。

a['Names'].str.lower().str.contains('mel').any()

如果你想保存结果,那么你可以使用这个:

a['result'] = a['Names'].apply(lambda x : ','.join([item for item in str(x).split() if item.lower() in ['mel', 'etc']]))

import pandas as pd将熊猫导入为 pd
(data_frame.col_name=='str_name_to_check').sum() (data_frame.col_name=='str_name_to_check').sum()

import re
s = 'string'

df['Name'] = df['Name'].str.findall(s, flags = re.IGNORECASE)

#or
df['Name'] = df[df['Name'].isin(['string1', 'string2'])]

You should check the value of your line of code like adding checking length of it.您应该检查代码行的值,例如添加检查长度。

if(len(a['Names'].str.contains('Mel'))>0):
    print("Name Present")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM