pierre_j
pierre_j

Reputation: 983

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

Upvotes: 0

Views: 316

Answers (2)

Acccumulation
Acccumulation

Reputation: 3591

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']

Upvotes: 1

It_is_Chris
It_is_Chris

Reputation: 14113

You need to access each teo object individually. One way to do this is through list comprehension.

df.iloc[[i for i,v in df['c'].iteritems() if v.a=='b']]

Upvotes: 0

Related Questions