Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
Selected Reading
Write a program in Python to filter only integer elements in a given series
Input − Assume you have the following series −
0 1 1 2 2 python 3 pandas 4 3 5 4 6 5
Output − The result for only integer elements are −
0 1 1 2 4 3 5 4 6 5
Solution 1
Define a Series.
Apply lambda filter method inside a regular expression to validate digits and expression accepts only strings so convert all the elements into strings. It is defined below,
data = pd.Series(ls) result = pd.Series(filter(lambda x:re.match(r"\d+",str(x)),data))
Finally, check the values using the isin() function.
Example
Let us see the following implementation to get a better understanding.
import pandas as pd ls = [1,2,"python","pandas",3,4,5] data = pd.Series(ls) for i,j in data.items(): if(type(j)==int): print(i,j)
Output
0 1 1 2 4 3 5 4 6 5
Solution 2
Example
import pandas as pd import re ls = [1,2,"python","pandas",3,4,5] data = pd.Series(ls) result = pd.Series(filter(lambda x:re.match(r"\d+",str(x)),data)) print(data[data.isin(result)])
Output
0 1 1 2 4 3 5 4 6 5
Advertisements
