Abstract: implement nested dictionary to store data frame as in R
The script:
# -*- coding: utf-8 -*-
"""
Created on Sat Aug 1 17:57:36 2015
@author: yuan
"""
import numpy as np
import pandas as pd
#create a data frame like in R
l=range(12)
df=np.array(l).reshape((3,4))
df=pd.DataFrame(df,columns=['a','b','c','d'], index=['a1','a2','a3'])
print df
#convert df to dictionary
d={}
for row_index,row in df.iterrows():
d[row_index]=row
for col_name in df.columns:
print row_index, col_name, row[col_name]
print 'Nested dictionary:', d
print 'rowname:a2, colname:c =', d['a2']['c']
print 'convert dictionary to df:'
print pd.DataFrame(d)
No comments:
Post a Comment