1

I want to convert a dataframe column to list of list as below:

df = pd.read_csv('xyz.csv')
print(df.head())
dataset = df.passenger_count.values.astype('float32')
print(dataset[:10])

Output:

     month   passenger_count
0  1949-01        112
1  1949-02        118
2  1949-03        132
3  1949-04        129
4  1949-05        121

[112. 118. 132. 129. 121. 135. 148. 148. 136. 119.]

I want output to be like this:

[[112.] [118.] [132.] [129.] [121.] [135.] [148.] [148.] [136.] [119.]]
Lalit Jain
  • 363
  • 2
  • 14

1 Answers1

1

you just need to reshape your numpy array and it will be as you expect :

dataset.reshape((-1,1)).tolist()
>[[112.], 
  [118.],
  [132.],
  [129.],
  [121.],
  [135.],
  [148.],
  [148.],
  [136.],
  [119.]]

or as @cs96 suggested in comments :

df[['passenger_count']].to_numpy().tolist()

will result in the same thing...

Note : just avoid the tolist() if you want to stay as numpy array...

adir abargil
  • 5,495
  • 3
  • 19
  • 29