
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
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
- Related Articles
- Write a program in Python to filter valid dates in a given series
- Write a program in Python to filter armstrong numbers in a given series
- Python program to filter perfect squares in a given series
- Write a Python program to shuffle all the elements in a given series
- Write a program in Python to round all the elements in a given series
- Write a program in Python to filter the elements in a series which contains a string start and endswith ‘a’
- Write a program in Python to sort all the elements in a given series in descending order
- Write a program in Python to print the power of all the elements in a given series
- Write a program in Python to filter City column elements by removing the unique prefix in a given dataframe
- Write a program in Python to find the missing element in a given series and store the full elements in the same series
- Write a program in Python to count the total number of integer, float and object data types in a given series
- Write a program in Python to print the elements in a series between a specific range
- Write a Python code to filter palindrome names in a given dataframe
- Write a program in Python to slice substrings from each element in a given series
- Write a program in Python to check if a series contains duplicate elements or not

Advertisements