【问题标题】:How to split a string and update the dictionary in csv file in python?如何在python中拆分字符串并更新csv文件中的字典?
【发布时间】:2015-11-11 13:23:18
【问题描述】:

所以我有一个包含股票数据的 csv 文件,格式如下:

日期,"开盘价","最高价","最低价"

2012-11-14,660.66,662.18,123.4

我已成功将所有相关数据转换为正确的变量类型,即所有 Open 值都是浮点数,High 是浮点数,日期是字符串

这是我目前的代码:

    types = [ ("Date", str), ("Open",float), ("High", float),
      ("Low", float), ("Close", float), ("Volume", int), ("Adj Close", float) ]

    with open("googlePrices.csv") as f:
        for row in csv.DictReader(f):  # read a row as {col1: val1, col2: val2..}
            row.update((key, conversion(row[key])) for key, conversion in types)

如何去除每个日期值,以便日期值中没有“-”?然后将它们转换为整数?我尝试使用日期时间,但我无法真正理解它。

【问题讨论】:

    标签: python csv dictionary strip


    【解决方案1】:

    消除-s 并将生成的字符串转换为整数可能对您没有帮助。你绝对想使用DateTime,更具体地说是strptime:

    classmethod datetime.strptime(date_string, format)

    返回一个date_string对应的datetime,根据解析 格式。这相当于 datetime(*(time.strptime(date_string, 格式)[0:6]))。如果 date_string 和 format 不能被 time.strptime() 解析,或者如果它返回一个值 不是时间元组。有关格式化指令的完整列表,请参阅 strftime() 和 strptime() 部分的行为。

    例如:

    datetime.datetime.strptime('2012-11-14','%Y-%m-%d')
    #datetime.datetime(2012, 11, 14, 0, 0)
    

    此外,您似乎有一个财务时间序列。无需读取 CSV 并手动解析。 Pandas 可以很好地满足您的需求。

    【讨论】:

    • 感谢您的回答!我是python新手,这个方法的代码是什么? row['Date'] = datetime.strptime(row['Date'], '%y %m %d') 然后我要再更新字典吗??
    • 因为您的格式是2012-11-14,所以掩码(strptime 中的第二个参数)将是 '%y-%m-%d'
    • 我的代码现在是:types = [ ("Date", str), ("Open",float), ("High", float), ("Low", float), ("Close", float), ("Volume", int), ("Adj Close", float) with open("googlePrices.csv") as f: for row in csv.DictReader(f): # read a row as {col1: val1, col2: val2..} row.update((key, conversion(row[key])) for key, conversion in types) row['Date'] = time.strptime(row['Date'], '%y-%m-%d') print(row),我得到了错误:/ValueError: time data '2012-11-14' does not match format '%y-%m-%d'
    • 应该是%Y 而不是%y。我用一个代码工作示例编辑了我的答案。
    • 非常感谢!!如何再次更新字典以使新日期在其中??
    【解决方案2】:

    由于数据保存在csv文件中,读取后只是字符串,如果Date的格式是固定的,那么只需简单地删除-即可。

    types = [ ("Date", int), ("Open",float), ("High", float),
          ("Low", float), ("Close", float), ("Volume", int), ("Adj Close", float) ]
    
    rowlist = []
    
    with open("googlePrices.csv") as f:
        for row in csv.DictReader(f):
            row['Date'] = row['Date'].replace('-','')
            try:
                row.update((key, conversion(row[key])) for key, conversion in types)
            except KeyError:
                continue 
            rowlist.append(row)
    

    输出:

    >>> print rowlist
    [{'Date': 20121114, 'High': 662.18, 'Open': 660.66, 'Low': 123.4}]
    

    如果您想将Date 转换为timestamp,请使用:

    >>>time.mktime(time.strptime('2012-11-14', '%Y-%m-%d'))
    1352822400.0
    

    【讨论】:

    • 如果我这样做,我将如何比较日期?我需要找到每月的平均成本,那么我将如何比较日期,以便我可以阅读数据以及月份变化何时停止并返回平均值?然后继续下个月?
    • 如果你想比较日期,你最好不要将Date转换为int类型,保存像{'Date': time.strptime('2012-11-14', '%Y-%m-%d'),...}这样的行然后你可以做a= [row['Open'] for row in rowlist if row['Date'].tm_year==2012 and row['Date'].tm_mon == 9 ] sum(a)/len(a) 得到@987654331 @ 2012-09 的平均值。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多