Python 如何在将字典转换为数据帧时设置索引?
我有一本字典,看起来像下面的Python 如何在将字典转换为数据帧时设置索引?,python,pandas,dictionary,Python,Pandas,Dictionary,我有一本字典,看起来像下面的 defaultdict(list, {'Open': ['47.47', '47.46', '47.38', ...], 'Close': ['47.48', '47.45', '47.40', ...], 'Date': ['2016/11/22 07:00:00', '2016/11/22 06:59:00','2016/11/22 06:58:00', ...]}) 我的目的是将此字典转换为数据帧,并将“D
defaultdict(list,
{'Open': ['47.47', '47.46', '47.38', ...],
'Close': ['47.48', '47.45', '47.40', ...],
'Date': ['2016/11/22 07:00:00', '2016/11/22 06:59:00','2016/11/22 06:58:00', ...]})
我的目的是将此字典转换为数据帧,并将“Date”键值设置为数据帧的索引
我可以通过以下命令来完成这项工作
df = pd.DataFrame(dictionary, columns=['Date', 'Open', 'Close'])
0 Date Open Close
1 2016/11/22 07:00:00 47.47 47.48
2 2016/11/22 06:59:00 47.46 47.45
3 2016/11/22 06:58:00 47.38 47.38
df.index = df.Date
Date Date Open Close
2016/11/22 07:00:00 2016/11/22 07:00:00 47.47 47.48
2016/11/22 06:59:00 2016/11/22 06:59:00 47.46 47.45
2016/11/22 06:58:00 2016/11/22 06:58:00 47.38 47.38
但是,我有两个“日期”列,一个是索引,另一个是原始列
在将字典转换为dataframe时,是否有任何方法可以设置索引,而不会出现如下重叠列
Date Close Open
2016/11/22 07:00:00 47.48 47.47
2016/11/22 06:59:00 47.45 47.46
2016/11/22 06:58:00 47.38 47.38
感谢您阅读此文!:) 使用:
或者使用就地:
df = pd.DataFrame(dictionary, columns=['Date', 'Open', 'Close'])
df.set_index('Date', inplace=True)
print (df)
Open Close
Date
2016/11/22 07:00:00 47.47 47.48
2016/11/22 06:59:00 47.46 47.45
2016/11/22 06:58:00 47.38 47.40
另一种可能的解决方案是通过Date
键过滤掉dict
,然后通过dictionary['Date']
设置索引:
df = pd.DataFrame({k: v for k, v in dictionary.items() if not k == 'Date'},
index=dictionary['Date'],
columns=['Open','Close'])
df.index.name = 'Date'
print (df)
Open Close
Date
2016/11/22 07:00:00 47.47 47.48
2016/11/22 06:59:00 47.46 47.45
2016/11/22 06:58:00 47.38 47.40
很高兴能帮助你!如果我的回答有帮助,别忘了。谢谢。谢谢你详细的回答!我可以请你对最后一个解决方案作更多的解释吗?我不容易理解DataFrame()命令中的内容。k和v代表什么?它类似于列表理解吗?是的,它是dict理解,非常类似于列表理解,只是输出是另一个或更改的原始dict。
df = pd.DataFrame({k: v for k, v in dictionary.items() if not k == 'Date'},
index=dictionary['Date'],
columns=['Open','Close'])
df.index.name = 'Date'
print (df)
Open Close
Date
2016/11/22 07:00:00 47.47 47.48
2016/11/22 06:59:00 47.46 47.45
2016/11/22 06:58:00 47.38 47.40