Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Select column containing several value with range of number in pandas

If I have a dataframe `

A            Variant&Price                Qty
AAC           7:124|25: 443                1
AAD             35:|35:                    1
AAS           32:98|3:40                   1
AAG             2: |25:                    1
AAC          25:443|26:344                 1

and I want to get variant which has one of its values is below 7

A            Variant&Price                 Qty
AAC           7:124|25: 443                1
AAS            32:9|3:40                   1
AAG             2: |25:                    1

Note that first digit is the variant, as well as the third digit (variant always before :)
I can apply this code,

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

split_df = df['Variant&Price'].str.split(':|\|', expand=True)
print(df[split_df.iloc[:, [0,2]].astype(int).min(axis=1) <= 7])

But what if I want to get, instead of 7, it is now range from 2 to 7. I ve tried >=2 & <=7 but not working

>Solution :

You can use a regex to extractall the number before :, convert to integer and check if any is between 2 and 7:

m = (df['Variant&Price'].str.extractall('(\d+):')[0]
     .astype(int).between(2,7).groupby(level=0).any()
    )

out = df[m]

Output:

     A  Variant&Price  Qty
0  AAC  7:124|25: 443    1
2  AAS     32:98|3:40    1
3  AAG        2: |25:    1
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading