我有這個csv:
ref,columns,start,end,content
1,Column1,1234,5654, text11
1,Column2,2454, 3223, text12
1,Column3,7565,8765, text13
1,Column4,8524, 5456, text14
1,Column5,1235, 5245, text15
2,Column1,7856, 2356, text21
2,Column2,4568, 3545, text22
2,Column3,5756, 4563, text23
2,Column4,9856, 2135, text24
2,Column5,4535,5456, text25
3,Column1,5756, 9856,text31
3,Column2,5764,8778,text32
3,Column3,1536,8768,text33
3,Column4,6861, 5654,text34
3,Column5,6875, 6586, text35
我怎樣才能把它改成這樣的字典? 讓'ref'也成為一個列,并在輸出中洗掉開始和結束。
thisdict = {
"ref": [1,2,3] 。
"Column1": ['text11','text21','text31'] 。
"Column2": ['text12','text22','text32'] 。
"Column3": ['text13','text23','text33'] 。
"Column4": ['text14','text24','text34'] 。
"Column5": ['text15','text25','text35']。
}
這是我所嘗試的:
這是我所嘗試的。
Columns = "Column1"/span>,"Column2", "Column3"/span>,"Column4"/span>,"Column5"/span>.
cols = col1,col2,col3,col4,col5 = [],[],[],[] 。
with open(csvfile,'r'/span>,encoding="utf8"/span>) as f:
reader = list((csv.reader(f)) )
for line in reader:
for i,col in enumerate(Columns):
if col == line[1] 。
cols[i].append(line[4] )
for col in cols:
print(col)
輸出:
['text11'/span>, 'text21'/span>, 'text31'/span>]
['text12'/span>, 'text22'/span>, 'text32']
['text13'/span>, 'text23'/span>, 'text33']
['text14'/span>, 'text24'/span>, 'text34']
['text15'/span>, 'text25'/span>, 'text35'/span>]
謝謝你的幫助
uj5u.com熱心網友回復:
import pandas as pd
path_to_file = "xxx"/span>
df = pd.read_csv(path_to_file)
df = df.reset_index()
del df['start']
del df['End']
this_dict = df.to_dict()
uj5u.com熱心網友回復:
做一些像這樣簡單的事情:
thisdict = {
"ref"/span>: [],
}
with open("your.csv"/span>) as csv_fp。
for line in csv_fp:
if line.startswith("ref")。
# 跳過第一行。
繼續。
ref, col, _, _, content = line.strip().split(",")
if int(ref) not in thisdict["ref"] 。
thisdict["ref"].append(int(ref))
if col not in thisdict:
thisdict[col] = [content](內容)。
else:
thisdict[col].append(content)
print(thisdict)
uj5u.com熱心網友回復:
我想把你的代碼改一下。試試這個:
from collections import defaultdict
import csv
col_dict = defaultdict(list)
with open(csvfile,'r'/span>,encoding="utf8"/span>) as f.
reader = csv.DictReader(f)
for row in reader:
col_dict[row['columns']].append(row['content'] )
if int(row['ref']) not in col_dict['ref'] 。
col_dict['ref'].append(int(row['ref'))
print(col_dict)
csv.DictReader允許你把你的csv的每一行作為一個字典讀取。這是可能的,因為你的 csv 有頭檔案。
defaultdict允許你創建一個字典,其中的值將默認為你傳遞給它的任何文字或函式,在這種情況下,list,它創建一個空串列。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/327673.html
標籤:
上一篇:在實施Stripe時,我如何使用Express(或其他方法)重定向?
下一篇:Web前端安全之安全編碼原則
