spliting the value by delimiter pandas

In my dataframe, I have a column called pca that has 2 values.

dataframe

I want to separate them into 2 columns.

My thinking was that, I separate them using str.split and after that remove the square bracket in each column.

I tried using
getClusterReview[['pca_A', 'pca_B']] = getClusterReview['pca'].str.split(',', expand=True)

However, I am stuck at splitting as I got an error saying column must be the same length.

>Solution :

First create the lists with the values that will be your splitted columns, and then add them to the df, and drop the old column if you want:

pca1 = []
pca2 = []
for element in getClusterReview["pca"]:
  pca1.append(element[0])
  pca2.append(element[1])

getClusterReview["pca1"] = pca1
getClusterReview["pca2"] = pca2
getClusterReview.drop("pca", axis=1)
   

Leave a Reply