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?
>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)