【问题标题】:Reading items from a csv and updating the same items in another csv从 csv 读取项目并更新另一个 csv 中的相同项目
【发布时间】:2019-07-08 12:57:15
【问题描述】:

我正在研究一种从input.csv 读取数据的方法,并根据产品的id 更新output.csv 中的stock

这些是我现在正在做的步骤:

1.将产品信息从input.csv读入input_data = [],这将返回一个OrderedDict列表。

input_data 目前看起来像这样:

[OrderedDict([('id', '1'), ('name', 'a'), ('stock', '33')]), OrderedDict([('id', '2'), ('name', 'b'), ('stock', '66')]), OrderedDict([('id', '3'), ('name', 'c'), ('stock', '99')])]

2. 将当前产品信息从output.csv 读入output_data = [],与input_data 具有相同的架构

3. 遍历input_data 并根据input_data 中的股票信息更新output_data 中的stock 列。 最好的方法是什么?

-> 重要的一点是input_data 可能有一些 ID 存在于input_data 但不存在于output_data。我想为input_dataoutput_data 共同的ids 更新股票,并且“新”ids 很可能会被写入新的 csv。 p>

我在想类似的东西(这不是真正的代码):

for p in input_data:
    # check if p['id'] exists in the list of output_data IDs (I might have to create a list of IDs in output_data for this as well, in order to check it against input_data IDs
    # if p['id'] exists in output_data, write the Stock to the corresponding product in output_data
    # else, append p to another_csv

我知道这看起来很混乱,我要的是一种合乎逻辑的方式来完成这项任务,而不会浪费太多的计算时间。有问题的文件可能有 100,000 行长,因此性能和速度将是一个问题。

如果我来自 input_dataoutput_data 的数据是 listOrderedDict ,那么检查 input_data 中的 id 并将 stock 写入产品的最佳方法是output_data 中的 id 完全相同?

【问题讨论】:

标签: python list csv ordereddict


【解决方案1】:

虽然 Python 可能不是您的最佳选择,但我不会为此任务使用 OrderDict 列表。这仅仅是因为尝试在output_data 中更改某些内容需要 O(n) 复杂度,这只会将您的脚本转换为 O(n**2)。 我会将这两个文件保存在 dicts 中(或者如果您关心订单,则为 OrderedDicts),就像这样(并将整个事情的复杂性降低到 O(n)):

input_data = {
    '1': ['a', '33'],
    '2': ['b', '66'],
    '3': ['c', '99']
}
output_data = {
    '1': ['a', '31'],
    '3': ['c', '95']
}

# iterate through all keys in input_data and update output_data
# if a key does not exist in output_data, create it in a different dict
new_data = {}
for key in input_data:
    if key not in output_data:
        new_data[key] = input_data[key]
        # for optimisation's sake you could append data into the new file here
        # and not save into a new dict
    else:
        output_data[key][1] = input_data[key][1]
        # for optimisation's sake you could append data into a new output file here
        # and rename/move the new output file into the old output file after the script finishes

【讨论】:

  • 谢谢,这让我朝着正确的方向前进,这就是我希望使用的那种数据结构。但是,我似乎无法以这种格式从 csv 读取数据,因此每一行都是'1' : ['a', '33']。请问有什么技巧可以做到这一点吗?
  • 我猜你是逐行阅读的,它类似于 data = line.split(separator),然后 input_data[data[0]] = data[1:]。
  • 谢谢! Mulțumesc :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-24
  • 1970-01-01
  • 2017-05-24
  • 1970-01-01
  • 2023-03-05
相关资源
最近更新 更多