将数据帧转换为列表列表

时间:2017-02-07 14:39:01

标签: python pandas

我有这个数据框:

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

我希望将此数据框转换为列表列表,如下所示:

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

我尝试df.valuesdf.values.tolist()并始终收到:

[[ nan]
 [   2]
 [   1]]

2 个答案:

答案 0 :(得分:8)

如果您致电reset_index恢复索引,则可以致电.values.tolist()以获得所需的结果:

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返回一个numpy数组,它有一个方法tolist()来转换为列表列表

答案 1 :(得分:5)

首先需要DataFrame.reset_indexDataFrame.values返回numpy arraytolist()将其转换为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]]

但如果需要DatetimeIndex,请astypeindex转换为string

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]]