簡體   English   中英

在 Python 中將 CSV 文件轉換為字典時轉換數據類型

[英]Casting Data Types When Converting a CSV file to a Dictionary in Python

我有一個看起來像這樣的 CSV 文件

Item,Price,Calories,Category
Orange,1.99,60,Fruit
Cereal,3.99,110,Box Food
Ice Cream,6.95,200,Dessert
...

我想以這種格式形成一個 Python 字典:

{'Orange': (1.99, 60, 'Fruit'), 'Cereal': (3.99, 110, 'Box Food'), ... }

我想確保刪除列的標題(即不包括第一行)。

這是我迄今為止嘗試過的:

reader = csv.reader(open('storedata.csv'))

for row in reader:
    # only needed if empty lines in input
    if not row:
        continue
    key = row[0]
    x = float(row[1])
    y = int(row[2])
    z = row[3]
    result[key] = x, y, z

print(result)

但是,當我這樣做時,我得到一個ValueError: could not convert string to float: 'Price' ,我不知道如何解決它。 我想將這三個值保存在一個元組中。

謝謝!

我建議使用pandas.read_csv來讀取您的csv文件:

import pandas as pd

df = pd.DataFrame([["Orange",1.99,60,"Fruit"], ["Cereal",3.99,110,"Box Food"], ["Ice Cream",6.95,200,"Dessert"]],
            columns= ["Item","Price","Calories","Category"])

我試圖將您的數據框起來,如下所示:

print(df)
    Item         Price    Calories    Category
0   Orange       1.99       60          Fruit
1   Cereal       3.99       110         Box Food
2   Ice Cream    6.95       200         Dessert

首先,創建一個空的Python dictionary來保存文件,然后利用pandas.DataFrame.iterrows()遍歷列

res = {}


for index, row in df.iterrows():
    item = row["Item"]
    x = pd.to_numeric(row["Price"], errors="coerce")
    y = int(row["Calories"])
    z = row["Category"]
    res[item] = (x,y,z) 

事實上,打印res會產生您expected output ,如下所示:

print(res)

{'Orange': (1.99, 60, 'Fruit'),
 'Cereal': (3.99, 110, 'Box Food'),
 'Ice Cream': (6.95, 200, 'Dessert')}

如果您使用的是名為dfpandas.DataFrame ,則可以簡單地使用dictzip

>>> dict(zip(df['Item'], df[['Price', 'Calories', 'Category']].values.tolist()))
{'Orange': [1.99, 60, 'Fruit'], 'Cereal': [3.99, 110, 'Box Food'], 'Ice Cream': [6.95, 200, 'Dessert']}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM