Yesterday I was wondering how to access to dictionary keys in a DataFrame column (link). The solution was to use .str[<key>]
on the pandas Series and call the tolist()
method afterwards. However this does not work with object attributes.
My goal is to get as an output a list of a specific attributes for each object in a panda Series.
Here is a sample code with the solution I am working with. I cast the whole object Series as a list and then iterate over it to get the specific attribute. Is there a way to access directly the attribute ?
class User:
def __init__(self, name):
self.name = name
df = pd.DataFrame({
'col1': [User("Juan"), User("Karen"), User("Vince")]
})
myObjects = df['col1'].tolist()
myNames = [u.name for u in myObjects]
# Desired output
['Juan', 'Karen', 'Vince']
And when I try the dictionary solution :
myNames = df["col1"].str['name'].tolist()
# Output
[nan, nan, nan]