How to set index when converting dictionary to dataframe?

I have a dictionary that looks like below

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', ...]}) 

My goal is to convert this dictionary into a data framework and set the Date key values ​​as the index of the data frame.

I can complete this task with the following commands

 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 

but then I have two Date columns, one of which is the index and the other is the original column.

Is there a way to set the index while converting the dictionary to dataframe without column matches, as shown below?

  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 

Thanks for reading this! :)

+5
source share
1 answer

Use set_index :

 df = pd.DataFrame(dictionary, columns=['Date', 'Open', 'Close']) df = df.set_index('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 

Or use inplace :

 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 

Another possible solution is to filter the dict with the Date key, and then set the index to 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 
+4
source

Source: https://habr.com/ru/post/1261447/


All Articles