[英]Pandas DataFrame read_csv first column as key in dictionary and second column as value (in a simple way)
[英]Read a csv to dictionary with particular column value as key
我正在嘗試將CSV讀入python的字典中
Name Value time count
sample A 00:00 45
sample A 01:00 46
sample A 02:00 50
sample A 03:00 85
sample A 04:00 87
abb B 00:00 40
abb B 01:00 55
我希望輸出為:
{ A:[{time:00:00 ,count:45},{time:01:00,count:46},{time:02:00,count:50}]}
有人可以幫我獲得輸出嗎?
我嘗試了dict理解,我能夠將csv讀取為字典,其中鍵作為列標題,值作為行,但不確定如何獲取上述輸出。
讀入文件,然后拆分為抽象鍵和值
with open(file,'rb') as f:
res = {}
reader = csv.reader(f)
for i,line in enumerate(reader):
if i == 0: continue
keyWord = line.split(' ')[1]
timeKeyword = 'time:' + line.split(' ')[2]
countValue = line.split(' ')[3]
res[keyWord ] = res.get(keyWord,[]) + [{timeKeyword : int(countValue )}]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.