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

Search csv and return value next to it

I’m working on a simple data filters and I need help with this task:

Let’s say this is my .csv file:

08534710,2888,15
08583315,2999,5

My goal here is to write a function that will search for given value (e.g. 2888) and return value next to it (15)
Here’s my code so far:

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

def wordfinder(searchstring):
    csv_file = pd.read_csv('test.csv', "r")
    for searchstring in csv_file:
        if searchstring in csv_file:
            print(searchstring[2])
            return searchstring[2]

But I don’t think it works as intended.

>Solution :

Search the searchstring into the second column and return the values of the third column:

def wordfinder(searchstring):
    df = pd.read_csv('test.csv', dtype=str, header=None)
    return df.loc[df[1] == searchstring, 2]

Output:

>>> wordfinder('2888')
0    15
Name: 2, dtype: object

# OR

>>> wordfinder('2888').tolist()
['15']
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