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?
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
+ 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)
+ 3
Just... filter()
https://book.pythontips.com/en/latest/map_filter.html
+ 2
Try this way:
https://code.sololearn.com/c57n8cO7TPMB/?ref=app
0
Bilbo Baggins , thank you for answer. Could you give an example, please?