Search code examples
pythonpandasgetattr

How accessing object attributes that are stored in a DataFrame to assess conditions?


Please, is there any way to assess conditions on object attributes through loc when objects are stored in a pandas DataFrame?

Something like:

import pandas as pd
from dataclasses import dataclass 

@dataclass(order=True, frozen=True)
class teo(object):
    a : str

te = teo('b')
df = pd.DataFrame({'c':[te]})

df.loc[df['c'].getattr('a') == 'b']

Above example outputs:

AttributeError: 'Series' object has no attribute 'getattr'

Thanks for your help! Bests


Solution

  • Your syntax is incorrect; it should be getattr(teo, 'b')

    To broadcast that across a column, you can use apply and an anonymous function:

    df.loc[df['c'].apply(lambda x: getattr(x,'a')) == 'b']