我有这个数据框:
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.values
或df.values.tolist()
并始终收到:
[[ nan]
[ 2]
[ 1]]
答案 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]]
答案 1 :(得分:5)
首先需要DataFrame.reset_index
,DataFrame.values
返回numpy array
,tolist()
将其转换为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
,请astype
将index
转换为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]]