others - python - 如何從CSV讀取數據到嵌套的key-value,以便將來檢索?

我有一個CSV文件(data.csv ),如下所示:


Time,Data1,Data2,Data3


0,10,25,100


1,20,30,120


2,25,35,125


3,30,50,150



我試過:


import csv



dataFile = 'data.csv'



with open(dataFile) as inputData:


 csv_input = csv.reader(inputData)


 headers = next(csv_input)


 data = list(zip(*[map(int, row) for row in csv_input]))



my_list = list(zip(data[0], data[1:]))


my_dictionary = dict(zip(headers, my_list))



print(my_dictionary['Data1'][1])



但是,這將返回:


(25, 30, 35, 50)



我想返回:

 
20



时间: 作者:


import csv



dataFile = 'data.csv'



with open(dataFile) as inputData:


 csv_input = csv.reader(inputData)


 headers = next(csv_input)


 data = list(zip(*[map(int, row) for row in csv_input]))



修改成用字典很簡單:


my_dictionary = dict(zip(headers, data))



print(my_dictionary ['Data1'][1])


>>> 20



作者:

不需要載入這個巨大的Panda庫來讀取CSV文件,Python提供了以下模塊:





import csv


import collections



filename ="data_80.csv"



def read_csv(filename):


 columns = collections.defaultdict(list)


 with open(filename, 'rt') as file:


 rows = csv.DictReader(file)


 for row in rows:


 for key, val in row.items():


 columns[key].append(val)


 return dict(columns) 



data = read_csv(filename)



print(data) # data is a dictionary of list


{


'Time': ['0', '1', '2', '3'], 


'Data1': ['10', '20', '25', '30'], 


'Data2': ['25', '30', '35', '50'], 


'Data3': ['100', '120', '125', '150']


}



# You just can do 


print(data['Data1'][0])



作者:

使用Pandas。

像這樣


import pandas as pd



我從你提供的數據中創建了一個文件,


df = pd.read_csv('rcsv.csv')



print(df.head())



看起來像這樣


Time Data1 Data2 Data3


0 0 10 25 100


1 1 20 30 120


2 2 25 35 125


3 3 30 50 150



得到一個這樣的特定元素(第二列中的第二個元素,零索引)


print(df.iloc[1][1])



20



作者:

沒有pandas的解決方案:


import csv



dataFile = 'data.csv'



with open(dataFile) as inputData:


 csv_input = csv.reader(inputData)


 i = zip(next(csv_input), zip(*csv_input))


 data, (_, times) = {}, next(i)


 for k, line in i:


 for t, l in zip(times, line):


 data.setdefault(k, {}).setdefault(t, {})


 data[k][int(t)] = l



print(data['Data1'][1])



列印:

 
20



作者:
...