我有一個 python 腳本,可以將我的 dict 保存到 csv 中
我的字典具有以下結構:
dict_data= dict()
xplanes=[7,3,10,11]
field = ['T','V','U']
for ppl in xplanes:
dict_data[ppl] = dict()
for ff in field
dict_data[ppl][ff] = ...Some... numpy array
現在我將 dict 寫入一個 csv 檔案
with open('file.csv','w') as f:
write=csv.write(f)
for k,v in dict_data.items():
write.writerow([k,v])
csv 檔案具有以下結構:
7,"{'T': array([ 637525.25 ...... , ], dtype=float32)
, 'V': array([ 637525.25 ...... , ], dtype=float32)
, 'U': array([ 637525.25 ...... , ], dtype=float32)}"
3,"{'T': array([ 637525.25 ...... , ], dtype=float32) ....
"}
現在我正在努力閱讀該檔案并將其恢復為我曾經擁有的字典,即, dict_data
uj5u.com熱心網友回復:
它沒有我想象的那么順利,所以它有點難看但應該做
from numpy import array, float32
import re
txt="""
7,"{'T': array([1,2,3], dtype=float32)
, 'V': array([1,2,3], dtype=float32)
, 'U': array([1,2,3], dtype=float32)}"
3,"{'T': array([1,2,3], dtype=float32)
, 'V': array([1,2,3], dtype=float32)
, 'U': array([1,2,3], dtype=float32)}"
10,"{'T': array([1,2,3], dtype=float32)
, 'V': array([1,2,3], dtype=float32)
, 'U': array([1,2,3], dtype=float32)}"
11,"{'T': array([1,2,3], dtype=float32)
, 'V': array([1,2,3], dtype=float32)
, 'U': array([1,2,3], dtype=float32)}"
"""
splitter=re.compile('(^\d{1,2}),', re.MULTILINE)
get_k_v=re.compile("'([TUV])': (array[^)] \))")
splits=re.split(splitter, txt)
old_dict={}
for split in splits:
if split=='\n':
continue
elif split.isdigit():
k=int(split)
else:
res=re.findall(get_k_v, split)
old_dict[k]={k: eval(v) for k,v in res}
print(old_dict[7]['T'])
>>> [1. 2. 3.]
uj5u.com熱心網友回復:
從熊貓讀取帶有 read_csv 的 csv 檔案。然后使用 to_dict() 方法。
import pandas as pd
data = pd.read_csv("file.csv")
print(data.to_dict())
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/312960.html
上一篇:有沒有辦法將陣列格式的字典串列轉換為資料框中的各個列?
下一篇:如何為字典中的字符分配數字?
