Input − Assume you have a series,
0 fruits!! 1 *cakes* 2 $nuts 3 #drinks dtype: object
Input − The result for the total number of counts for more than one special character in a series is 2.
Let us try to find different solutions to this question.
Solution 1
To solve this, we will follow the steps given below −
Define a Series
Create special characters list of values.
Set the initial value of special character and total special char count value as 0.
Create a for loop and access all the values in the Series one by one and create an if condition to compare the value based on special character as follows −
for i in data: chars_count = 0 for j in list(i): if j in special_char: chars_count = chars_count+1
Set the if condition and check the count value. If count > 1, then print the total count.
It is defined below −
if(chars_count>1): total_count = total_count+1 print(total_count)
Solution 2
Alternatively, we can use regular expression and lambda function filter method to find the total count.
To solve this, we will follow the steps given below −
Define a series
Apply lambda filter method to validate the input based on special char ().
Find the length is more than one. It is defined below −
l=["fruits!!","*cakes*","$nuts","#drinks"] data=pd.Series(filter(lambda x:1<len(re.findall(r"\W",x)),l))
Example
Let us see the implementation to get a better understanding −
import pandas as pd import string l = ["Fruits!!","*Cakes*","$Nuts","#Drinks"] data = pd.Series(l) chars=string.punctuation special_char=list(chars) total_count = 0 for i in data: chars_count = 0 for j in list(i): if j in special_char: chars_count = chars_count+1 if(chars_count>1): total_count = total_count+1 print(total_count)
Solution 3
Example
import pandas as pd import re l=["fruits!!","*cakes*","$nuts","#drinks"] data=pd.Series(filter(lambda x:1<len(re.findall(r"\W",x)),l)) print("count:",len(data))
Output
The output of the above program is as follows −
2