Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I split a column that has an object onto multiple columns

my columns look like this:

A  B     objectToBeSplit
1  2  {0.223, 0.112, 0.441}
3  4  {0.423, 0.402, 0.593}

And I would like to have it like this:

A  B    C      D      E
1  2  0.223  0.112  0.441
3  4  0.423  0.402  0.593

How can I split the objectToBeSplit column in python?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

There are a couple of ways to achieve this

# Sample DataFrame
df = pd.DataFrame({
    'A': [1, 3],
    'B': [2, 4],
    'objectToBeSplit': ['{0.223, 0.112, 0.441}', '{0.423, 0.402, 0.593}']
})

# Splitting the 'objectToBeSplit' column
df[['C', 'D', 'E']] = df['objectToBeSplit'].str.strip('{}').str.split(', ', expand=True)

# Dropping the original 'objectToBeSplit' column
df = df.drop('objectToBeSplit', axis=1)

Approach 2:

# Create new columns C, D, E by splitting the values in the "objectToBeSplit" column
df[['C', 'D', 'E']] = pd.DataFrame(df['objectToBeSplit'].tolist()).applymap(float)

# Dropping the original 'objectToBeSplit' column
df = df.drop('objectToBeSplit', axis=1)

# Print the updated DataFrame
print(df)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading