2017-07-11 42 views
1

我有我想轉換到一定的JSON格式的熊貓數據幀:數據幀與東方索引和索引,以JSON等於行值

df = pd.DataFrame([['A',1,2,3],['B',2,3,4],['C','C',1,6],['D','D',9,7]], columns=['W','X','Y','Z']) 

df.set_index('W', inplace=True, drop=True, append=False) 

df 
    X Y Z 
W 
A 1 2 3 
B 2 3 4 
C C 1 6 
D D 9 7 

我希望得到一個JSON輸出如下:

output_json = {'A': {'X':1,'Y':2,'Z':3}, 'B': {'X':2,'Y':3,'Z':4}, 'C':{'Y':1,'Z':6}, 'D': {'Y':9,'Z':7} } 

這是我已經試過,但我不能得到期望的結果爲「C」和「d」鍵:

df.to_json(orient='index') 
'{"A":{"X":1,"Y":2,"Z":3},"B":{"X":2,"Y":3,"Z":4},"C":{"X":"C","Y":1,"Z":6},"D":{"X":"D","Y":9,"Z":7}}' 

^h解決這個問題嗎?也許這是我錯過的直截了當的事情。謝謝。

回答

1

你可以先轉換to_dict,然後使用嵌套的字典修真只過濾int值,最後對JSON使用dumps

import json 

d = df.to_dict(orient='index') 
j = json.dumps({k:{x:y for x,y in v.items() if isinstance(y, int)} for k, v in d.items()}) 
print (j) 
{"A": {"X": 1, "Y": 2, "Z": 3}, 
"C": {"Y": 1, "Z": 6}, 
"D": {"Y": 9, "Z": 7}, 
"B": {"X": 2, "Y": 3, "Z": 4}} 
+1

這個偉大的工程,感謝你的幫助! –

+0

很高興能幫到你!祝你好運! – jezrael