简体   繁体   English

如何从 CSV 文件中提取数据并导入 Python 中的字典?

[英]How to Extract Data from CSV file and import to a Dictionary in Python?

I'm new in python new developer, just started my intership.我是 python 新开发人员,刚开始实习。 So, I have a csv file with datas customized like that所以,我有一个 csv 文件,其中包含这样自定义的数据

Event Category,Event Label,Total Events,Unique Events,Event Value,Avg.事件类别,事件 Label,总事件,唯一事件,事件值,平均。 Value价值

From each row of the file I want to extract the labels of the ports (bellow) in an dictionary and add the total and unic events too.从文件的每一行中,我想在字典中提取端口(波纹管)的标签,并添加总事件和 unic 事件。 The total and unique events I have to sum them only the ports with same labels (not being dublicate).总的和独特的事件我必须只将它们与具有相同标签的端口相加(不重复)。 My datas look like that: 'Search,Santorin (JTR) - Paros (PAS) - Santorin (JTR),"2,199","1,584",0,0.00' I want my dictionary to look like that:我的数据看起来像这样: 'Search,Santorin (JTR) - Paros (PAS) - Santorin (JTR),"2,199","1,584",0,0.00'我希望我的字典看起来像这样:

data_file = 'Analytics.csv' ports_dict = { # "ATH-HER": [10000, 5000], # "ATH-JTR": [20000, 3500], # "HER-JTR": [100, 500] } data_file = 'Analytics.csv' ports_dict = { # "ATH-HER": [10000, 5000], # "ATH-JTR": [20000, 3500], # "HER-JTR": [100, 500] }

 data = 'Analytics.csv'
#row= 'Search,Santorin (JTR) - Paros (PAS) - Santorin (JTR),"2,199","1,584",0,0.00'
def extract_counts(data):
  ports = []
  for i in data.split('"')[1:]:
      ports.append(i.split('"')[0])
  return ports

An example from my code is this, when I'm running with the row runs ok when I'm using 'data' it gives me back an empty string.我的代码中的一个示例是这样的,当我使用“数据”时,当我使用行运行正常时,它会返回一个空字符串。 Can Anyone help me with this?谁能帮我这个?

extract_counts(data) Out[13]: [] extract_counts(data) Out[13]: []

What I have to do to run this for the whole csv Thank you for your help!我必须做什么才能为整个 csv 运行此程序谢谢您的帮助!

First of all, 'data' is just a string variable.首先,“数据”只是一个字符串变量。 In your loop, you are iterating over each character, not reading a file.在您的循环中,您正在迭代每个字符,而不是读取文件。 Using split on a single character with '"', results in an empty string.对带有 '"' 的单个字符使用 split 会产生一个空字符串。

To begin your journey with reading CSV files in Python, I recommend:从阅读 Python 中的 CSV 文件开始您的旅程,我建议:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM