python filtering based on type of data | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

python filtering based on type of data

Hi! Does somebody know, how to filter series (there are different types in series: int, str, float) in python to get only values, which are integers? I have next code: s = pd.Series(data=['1', 2, 3.1, 'hi!', 5, -512, 12.42, 'sber', 10.10, 98], index=range(2, 12)) So I understand how to get type of each value in series. For example: type(s[3]) ---> int But how to do it for series?

11th Jan 2020, 12:38 PM
Павел Ефремов
Павел Ефремов - avatar
5 Answers
+ 1
Guys, the question is specific to pandas datatype Series. You can filter a pandas series by a boolean array. So first you can determine which indices contain int type, and pass this as a slice to the series. int_filter = s.apply(lambda e: type(e) == int) print(s[int_filter]) https://code.sololearn.com/ceEFi2Htw8s4/?ref=app
12th Jan 2020, 5:20 AM
Tibor Santa
Tibor Santa - avatar
+ 4
I am not sure if this is what you are looking for: # comprehension: data=['1', 2, 3.1, 'hi!', 5, -512, 12.42, 'sber', 10.10, 98] res = [val for val in data if isinstance(val, int)] # filter: res2 = list(filter(lambda x: isinstance(x, int), data)) print(res2) print(res)
11th Jan 2020, 1:32 PM
Lothar
Lothar - avatar
11th Jan 2020, 12:48 PM
Bilbo Baggins
Bilbo Baggins - avatar
11th Jan 2020, 1:38 PM
Sarthak
Sarthak - avatar
0
Bilbo Baggins , thank you for answer. Could you give an example, please?
11th Jan 2020, 1:12 PM
Павел Ефремов
Павел Ефремов - avatar