I worked with R very smoothly but now I want to work with Python. I have numerical values and into a data frame and now I want to filter specific values. I tried to find solution with other examples but unfortunately, I did find a useful example. Much of example are with strings not with specific numbers.
So first I want to show an example from R, these lines of code work very well.
filtered_data<-filtered_data<-%>%
dplyr::filter(items %in% c("2","3","4","5","6","7","14","20","19","23"))
Now I want to replicate these lines of code into Python and I try to do this
filtered_data<-source_data['items']==2,3,4,5,6,7,14,20,19,23]
So can anybody help me with how to filter these specific values in Python?
>Solution :
Use Pandas and isin:
filtered_data = source_data[source_data['items'].isin([2,3,4,5,6,7,14,20,19,23])]
print(filtered_data)
# Output
items
1 19
3 3
4 20
9 5
Setup a MRE:
import pandas as pd
import numpy as np
source_data = pd.DataFrame({'items': np.random.randint(1, 25, 10)})
print(source_data)
# Output
items
0 12
1 19
2 22
3 3
4 20
5 21
6 10
7 22
8 11
9 5