사전의 3 차원 독재로 저장된 여러 메트릭을 계산하는 코드가 있습니다. 이 사전을 csv 파일에 인쇄하고 싶습니다. 그러나 이렇게 좋은 방법을 찾지 못했습니다.다차원 사전을 파일로 작성
일단 사전 내의 모든 요소를 계산, 나는 (- 열 키와 열 측정 다른 periods
을 열 수 있어야 파일의 헤더와 keys
및 메트릭 a, b, and c
곳)가 파일로 인쇄하고 싶습니다.
파일로 인쇄하는 쉬운 방법이 있습니까? (내 첫 번째 시도는 팬더했지만이 작동하지 않았다)
감사
from collections import defaultdict
import pandas as pd
import os
import random
# 3 dimensional dictionary that stores integers
output_dict = defaultdict(lambda: defaultdict(lambda: defaultdict(int)))
# Array of periods
periods = range(0, 2)
# relevant keys
keys = ["key1", "key2"]
# Iterate over all periods
for period in periods:
# Iterate over all relevant keys
for key in keys:
# Store results for key for each time period for each category ("a", "b", or "c")
output_dict[key][period]["a"] += random.randint(1, 1000)
output_dict[key][period]["b"] += random.randint(1, 1000)
output_dict[key][period]["c"] += random.randint(1, 1000)
# This is the tricky part!!!
# Store results
pd.DataFrame(output_dict).to_csv("output_dict.csv", index=False)
# the dictionary may look as follows:
output_dict = {"key1": {0: {"a": 0.9, "b": 0.2, "c": 0.5}, 1:{"a": 0.91, "b": 0.3, "c": 0.4}},
"key2": {0: {"a": 0.4, "b": 0.33, "c": 0.34}, 1: {"a": 0.21, "b": 0.73, "c": 0.54}}}
첫째,와 팬더 Dataframe에 데이터를 변환 시도 'key','a','b','c'의 열. 그런 다음 CSV에 투기하는 것은 상당히 힘들어 야합니다. –
사전이 어떻게 생겼는지 예를 보여주고 csv를 어떻게 보이게 할 지 알려주는 것이 도움이 될 것입니다. –
@JackManey : 팬더에서 쉽게 할 수있는 방법이 있습니까? – Andreas