Home > Enterprise >  Convert list of 1-D array elements in dataframe column to regular numeric values
Convert list of 1-D array elements in dataframe column to regular numeric values

Time:02-23

have implemented ANN regression on a dataset. The predicted values and actual values are stored in a data frame. The actual values are of type float, where as predicted values in the dataframe are shown as type object when I have checked it using df.info().

The predicted values in the dataframe are similar to the below code:

import pandas as pd
a=[[1.4],[3.6],[6.7]]
df = pd.DataFrame()
df['a']=a

However, I want df['a'] to give the following output.

df['a'] = 1.4 3.6 6.7

I have tried df['a'].astype(float),df['a'].flatten(), but they didn't work. How to covert list of 1 d array elements in the dataframe column to normal floating values.

CodePudding user response:

You achieve it using numpy and list like this:

list(np.squeeze(a))

CodePudding user response:

import pandas as pd
a = [[1.4], [3.6], [6.7]]
df = pd.DataFrame(a, dtype=float, columns=["a"])

print(df["a"])
>>> 0    1.4
    1    3.6
    2    6.7
    Name: a, dtype: float64

This code directly uses the data as input for the dataframe. dtype indicates that the data consists of floats.

The columns argument must be an iterator. This is why a is inside a list.

To convert the pd.Series object to a list, run the following code:

print(df["a"].tolist())
>>> [1.4, 3.6, 6.7]
  • Related