将具有分层索引列的DataFrame导出/导入到JSON / CSV

时间:2019-08-27 21:16:33

标签: python json pandas csv dataframe

是否可以从JSON / CSV导入具有层次结构索引列的DataFrame?

这是我尝试过的方法,但似乎不起作用:

# input DataFrame
import pandas as pd
t = pd.DataFrame(data={'i1':[0,0,0,0,1,1,1,1,2,2,2,2],
                       'i2':[0,1,2,3,0,1,2,3,0,1,2,3],
                       'x1':[1,2,3,4,5,6,7,8,9,10,11,12],
                       'x2':[10,20,30,40,50,60,70,80,90,100,110,120],
                       'y1':[100,200,300,400,500,600,700,800,900,1000,1100,1200],
                       'y2':[1000,2000,3000,4000,5000,6000,7000,8000,9000,10000,11000,12000]})
t.set_index(['i1','i2'], inplace=True)
t.sort_index(inplace=True)
t.columns = pd.MultiIndex.from_product((('x','y'),(1,2)))

# trying to export/import it
pd.read_json( t.to_json() ) # fails
pd.read_csv ( t.to_csv () ) # fails

非常感谢您的帮助!

0 个答案:

没有答案