Search code examples
pythonpandasdataframenumeric

How can I convert a column with values like [1] (objects) to a numeric value?


I want to convert the following column (part of a DataFrame) into a numeric value.

df = pd.DataFrame({ "Cluster": [[0], [1], [0], [2]]})

My following code didn't work:

pd['Cluster_numeric'] = pd.to_numeric(df['Cluster'], errors='coerce')

Solution

  • This should work considering your length of the list is always 1

    df['Cluster_numeric']=df['Cluster'].apply(lambda x: x[0])