0

Assume I have a dataframe in Pandas:

import pandas as pd
import numpy as np
df = pd.DataFrame({'A': 'foo bar foo bar foo bar foo foo'.split(),
                   'B': 'one one two three two two one three'.split(),
                   'C': '0 1 2 3 4 5 6 7'.split(), 
                   'D': '0 2 4 6 8 10 12 14'.split()})

The dataframe df looks like

      A      B  C   D
 0  foo    one  0   0
 1  bar    one  1   2
 2  foo    two  2   4
 3  bar  three  3   6
 4  foo    two  4   8
 5  bar    two  5  10
 6  foo    one  6  12
 7  foo  three  7  14

Note that the type of numbers in C and D columns is string.

I'm thinking about two conditions:

(1) Consecutive search

I want to return the D values when I'm searching C=2:5. If I use df.loc[df['C'] == '2:5', "D"], it returns an error. How can I do this part?

(2) Discrete search

I'd like to return the D values when I'm searching C=0,3,6. Again, if I use df.loc[df['C'] == '0,3,6', "D"], it returns an error. What should I write this code?

1
  • You shouldn't be using strings to represent numerical values. Commented May 11, 2021 at 16:48

1 Answer 1

1

Consecutive Search:

The consecutive search method for a range of numerical strings can be taken care of by the isin() and zfill() method. The zfill method in the below code creates a list containing the range of the numbers:

df.D.loc[df.C.isin([str(i).zfill(1) for i in range(2,6)])]

Discrete Search

The discrete searching can be done by using the isin() method:

df.D.loc[(df.C.isin(['0','3','6'])]
Sign up to request clarification or add additional context in comments.

2 Comments

Yes, for the first case (consecutive searching), we can list them as you wrote. But if they're large interval, say 1:100, we can no longer list them. Is there a more convenient way?
@Thomas Thanks for this question, and it can be done pretty easily, please chek the edited answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.