Search code examples
pythonpandasstringlistisin

pass both string and list to pandas .isin method


I am trying to pass both a string and a list to the pandas .isin() method. Here is my code below

    overall_months = ['APR', 'JUL', 'NOV', 'MAR', 'FEB', 'AUG', 'SEP', 'OCT', 'JAN', 'DEC', 'MAY', 
    'JUN', ['APR', 'JUL', 'NOV', 'MAR', 'FEB', 'AUG', 'SEP', 'OCT', 'JAN', 'DEC', 'MAY', 'JUN']]

    for mon in overall_months:
        temp_df = df.month.isin([[mon]]))

The issue here is the .isin([]) is fine for each iteration of a string, but when i get to overall_months[-1], its a list and you cannot pass a list into .isin([]) syntax. Ive tried this but cannot remove the double quotes because my understanding is strings are immutable:

    str(overall_months[-1]).replace('[', '').replace(']','')

This produces: "'APR', 'JUL', 'NOV', 'MAR', 'FEB', 'AUG', 'SEP', 'OCT', 'JAN', 'DEC', 'MAY', 'JUN'" It could be passed to my syntax if it was: 'APR', 'JUL', 'NOV', 'MAR', 'FEB', 'AUG', 'SEP', 'OCT', 'JAN', 'DEC', 'MAY', 'JUN'

Any help in the best way to accomplish this?


Solution

  • You can check if the element is a list with isinstance:

    for mon in overall_months:
        if not isinstance(mon, list): 
            mon = [mon]
        tmp_df = df.month.isin(mon)