1

I have a dataframe in which contains different datatypes, here for example with two classes FirstGroup and LastGroup.

    id1                     id2                     id3...                               
0   (0, FirstGroup.Other)   (0, FirstGroup.Other)   (0, FirstGroup.Static)  ...    
1  (60, LastGroups.Other)  (22, LastGroups.Other)  (49, LastGroups.Static)  ... 

All of these objects have data stored that I want to pull out in an efficient way. One example would be: df['id1'].[0][1].name will give me a string variable 'type1'.

I want to have something like this:

    id1            id2            id3...                               
0   (0, 'type1')   (0, 'type1')   (0, 'type2')  ...    
1  (60, 'type1')  (22, 'type1')  (49, 'type2')  ... 

I am searching for something similar then the replace method but couldn't fine anything except looping over each row and column.

1 Answer 1

1

You can use applymap:

df.applymap(lambda x: (x[0], x[1].name))

full example:

class O:
    def __init__(self):
        self.name = str(id(self))[-5:]
    def __repr__(self):
        return 'CustomObject'

df = pd.DataFrame({'id%s' % i: [(j, O()) for j in range(2)] for i in range(3)})
df.applymap(lambda x: (x[0], x[1].name))

input:

                 id0                id1                id2
0  (0, CustomObject)  (0, CustomObject)  (0, CustomObject)
1  (1, CustomObject)  (1, CustomObject)  (1, CustomObject)

output:

          id0         id1         id2
0  (0, 95984)  (0, 98096)  (0, 97712)
1  (1, 97328)  (1, 98720)  (1, 97280)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.