-3

我需要导入具有此类数据的 CSV 文件,

                       January February March
              Amy      4     3      4
              Ben      5     2      0 
              Clara    0     3.5    4  

具有月份(名称)的第一行,具有名称(销售额)的第一列以及对应于月份的每月预订。

寻找一种方法来获得像这样的 Dictionary 输出,它需要用 0 删除月份

                {"Amy": {"January ": 4, "February": 3, "March": 4},
                  "Ben": {"January": 5, "February": 2},
                  "Clara": {"February": 3.5, "March": 4}}

任何帮助将不胜感激。

谢谢 ,

拉胡尔

4

3 回答 3

2

让我们假设您如何从 csv 获取数据到变量,检查唯一名称、无效数据……,并且您正在努力排除0值:

更新:读取我的代码中现在包含的 csv 文件:

# Python 3.2
import csv
delimiter = ','
result = {}
with open("data.csv", 'r') as data_file:
    data = csv.reader(data_file, delimiter=delimiter)
    headers = next(data)[1:] # month names starting from 2nd column in csv
    for row in data:
        temp_dict = {}
        name = row[0]
        values = []
        # converting each value from string to int / float
        # (as suggested by OP's example)
        for x in row[1:]:
            try:
                values.append(int(x))
            except ValueError:
                try:
                    values.append(float(x))
                except ValueError:
                    print("Skipping value '{}' that cannot be converted " +
                          "to a number - see following row: {}"
                          .format(x, delimiter.join(row)))
                    values.append(0)
        for i in range(len(values)):
            if values[i]: # exclude 0 values
                temp_dict[headers[i]] = values[i]
        result[name] = temp_dict    
print(result)
于 2012-06-19T14:16:41.160 回答
0

如果您知道 CSV 的分隔符,您可以执行以下操作:

tokens = line.split(delimiter)
tokens = [token.strip() for token in tokens]

...对于 CSV 的每一行。您需要从解析的第一行中提取适当的值以获取内部字典的键。之后,要获取最外层字典的键,您将使用tokens[0]等等。

现在,话虽如此,在我看来,您的 CSV 更像是一个固定宽度的文件,而不是 CSV。

于 2012-06-19T14:09:40.610 回答
0
import csv
ifile = open('test.csv', "rb")
reader = csv.reader(ifile)
rownum = 0
td = {'j': 0, 'f': 0, 'm': 0}
d = {}
for row in reader:
    # Save header row.
    if rownum == 0:
        header = row
    else:
        for c, col in enumerate(row):
            if c != 0:
                td[header] = col
        d[row[0]] = td
于 2012-06-19T14:24:56.873 回答