This is my .csv file generated using pandas. I am wanting to convert back to list type for the column of 'age' and 'studies'. But the '''dp.types''' show the type of age is '''object'''. All the elements are string, '[' '6' '8' ,'8' '3' ']'. Does anyone know how to convert back to the normal list with integer [68,83] [enter image description here]1
Asked
Active
Viewed 37 times
1 Answers
0
In order to convert a column in pandas to a list use:
# assuming df is your dataframe
df["column name"].to_numpy().to_list()
Which will first turn it into a numpy
array and them the numpy array (where are only numbers) to a list
Or convert the whole column to numeric data type and then to a list:
pd.to_numeric(df["column name"]).to_list()

John
- 197
- 1
- 3
- 14
-
2Why `to_numpy`? – roganjosh May 25 '20 at 00:16
-
I read somewhere that `.to_list()` may try to convert it into strings. Converting first into `numpy` assures us its going to be numbers – John May 25 '20 at 00:17
-
Just use [`astype`](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.astype.html) – roganjosh May 25 '20 at 00:21