【问题标题】:Casting Data Types When Converting a CSV file to a Dictionary in Python在 Python 中将 CSV 文件转换为字典时转换数据类型
【发布时间】:2020-04-13 12:16:34
【问题描述】:

我有一个如下所示的 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',我不知道如何解决它。 我想将这三个值保存在一个元组中。

谢谢!

【问题讨论】:

  • 这个错误的意思是在价格列中。有些行包含类似字符串。向我们展示reader 的样本数据。如果这是dataframe,您可以在阅读器上使用.info() 方法吗?
  • @PandasJ 我刚刚将其转换为 pandas DataFrame。这是信息:<class 'pandas.core.frame.DataFrame'> RangeIndex: 4 entries, 0 to 3 Data columns (total 4 columns): 0 4 non-null object 1 4 non-null object 2 4 non-null object 3 4 non-null object dtypes: object(4) memory usage: 256.0+ bytes

标签: python python-3.x dictionary tuples


【解决方案1】:

我建议使用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')}

【讨论】:

    【解决方案2】:

    如果您使用名为dfpandas.DataFrame,您可以简单地使用dict 加上zip

    >>> 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']}
    

    【讨论】:

    • 我想将其他项目放在一个元组中,而不是一个列表中。
    • 投反对票是为了什么?如果要将值转换为元组,就这么简单:dict(zip(df['Item'], map(tuple, df[['Price', 'Calories', 'Category']].values.tolist())))
    猜你喜欢
    • 2017-09-13
    • 1970-01-01
    • 2017-03-27
    • 2018-12-09
    • 2021-07-31
    • 1970-01-01
    • 2021-12-18
    • 2018-08-13
    • 2021-12-22
    相关资源
    最近更新 更多