简体   繁体   中英

convert dataframe to list of lists

I have this dataframe:

                     value
time
2016-12-01 00:00:00          NaN
2016-12-01 00:01:00          2
2016-12-01 00:02:00          1

I want convert this dataframe to a list of lists, likes this:

[['2016-12-01 00:00:00', NaN],['2016-12-01 00:01:00', 2],['2016-12-01 00:02:00', 1]]

I tried df.values or df.values.tolist() and always receive:

[[ nan]
 [   2]
 [   1]]

If you call reset_index to restore the index, you can then call .values.tolist() to get the desired result:

In [117]:
df.reset_index().values.tolist()

Out[117]:

[['2016-12-01 00:00:00', nan],
 ['2016-12-01 00:01:00', 2.0],
 ['2016-12-01 00:02:00', 1.0]]

values returns a numpy array, this has a method tolist() to convert to a list of lists

Need DataFrame.reset_index first, DataFrame.values return numpy array and tolist() convert it to nested list :

print (df.index)
Index(['2016-12-01 00:00:00', '2016-12-01 00:01:00', '2016-12-01 00:02:00'], 
 dtype='object', name='time')


print (df.reset_index().values.tolist())
[['2016-12-01 00:00:00', nan], ['2016-12-01 00:01:00', 2.0], ['2016-12-01 00:02:00', 1.0]]

But if DatetimeIndex is necessary convert index to string by astype :

print (df.index)
DatetimeIndex(['2016-12-01 00:00:00', '2016-12-01 00:01:00',
               '2016-12-01 00:02:00'],
              dtype='datetime64[ns]', name='time', freq=None)

print (df.reset_index().values.tolist())
[[Timestamp('2016-12-01 00:00:00'), nan], 
  [Timestamp('2016-12-01 00:01:00'), 2.0], 
  [Timestamp('2016-12-01 00:02:00'), 1.0]]

df.index = df.index.astype(str)
print (df.reset_index().values.tolist())
[['2016-12-01 00:00:00', nan], ['2016-12-01 00:01:00', 2.0], ['2016-12-01 00:02:00', 1.0]]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM