Home > Back-end >  How to turn column with lists into dataframe?
How to turn column with lists into dataframe?

Time:05-17

I have a dataset:

val
[0.5, 0.7,....,0.8]
[0.11, 0.4,....,0.77]
...
[0.99, 0.1,....,0.4]

it is pandas.core.series.Series

there are 1000 rows and 200 values in each list. I want to turn it into dataframe with 200 columns and 1000 rows, but when I do pd.DataFrame(list(df)) it says NumPy.float64 object is not iterable. How to fix it?

CodePudding user response:

You could use a dictionary comprehension:

import pandas as pd
s = pd.Series([[1,2,3],[4,5,6]])  # please provide a reproducible example
pd.DataFrame.from_dict({i:col for i,col in s.iteritems()})

returns

   0  1
0  1  4
1  2  5
2  3  6

You could also use from_records with a transpose:

pd.DataFrame.from_records(s).transpose()

CodePudding user response:

With the following data set:

data = pd.Series([[0.5, 0.7, 0.8],
[0.11, 0.4, 0.77]])

Doing

pd.DataFrame(data.values.tolist())

Would result in the expected result:

       0      1    2
0   0.50    0.7 0.80
1   0.11    0.4 0.77

CodePudding user response:

>>> data = pd.core.series.Series([[0.5, 0.7, 0.8],[0.11, 0.4, 0.77]])
>>> data
0      [0.5, 0.7, 0.8]
1    [0.11, 0.4, 0.77]
dtype: object
>>> l = data.values.tolist()
>>> l
[[0.5, 0.7, 0.8], [0.11, 0.4, 0.77]]
>>> pd.DataFrame(l)
      0    1     2
0  0.50  0.7  0.80
1  0.11  0.4  0.77
  • Related