0

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

pierre_j
  • 895
  • 2
  • 11
  • 26

2 Answers2

1

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']
Acccumulation
  • 3,491
  • 1
  • 8
  • 12
0

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']]
It_is_Chris
  • 13,504
  • 2
  • 23
  • 41