Python如何格式化CSV文件写入

时间:2014-12-05 04:28:55

标签: python csv

这是我的问题的图像: Image of problem

如何格式化CSV文件中的括号,以及如何将CSV中的值分隔在其他列中的“MODERATE”类别中?

以下是涉及CSV编写的代码部分。

combinedCSV = dict((k, [modCountNum[k], strCountNum.get(k)]) for k in modCountNum)
combinedCSV.update((k, [None, strCountNum[k]]) for k in strCountNum if k not in modCountNum)

combinedCSV2 = dict((k, [combinedCSV[k], majCountNum.get(k)]) for k in combinedCSV)
combinedCSV2.update((k, [None, majCountNum[k]]) for k in majCountNum if k not in combinedCSV)

combinedCSV3 = dict((k, [combinedCSV2[k], greCountNum.get(k)]) for k in combinedCSV2)
combinedCSV3.update((k, [None, greCountNum[k]]) for k in greCountNum if k not in combinedCSV2)

categoryEQ = ["REGION", "MODERATE", "STRONG", "MAJOR", "GREAT", "OVERALL"] #row setup for CSV file
csvEarthquakes = csv.writer(open('results.csv', 'w'), lineterminator='\n', delimiter=',') #creating results.csv
csvEarthquakes.writerow(categoryEQ)
csvEarthquakes.writerows(combinedCSV3.items())

3 个答案:

答案 0 :(得分:2)

您可以使用Pandas来执行此操作。

import pandas as pd

data = pd.DataFrame({'moderate':modCountNum, 'strong':strCountNum, 
                     'major':majCountNum, 'great':greCountNum})

data.to_csv('/tmp/results.csv')

答案 1 :(得分:0)

我假设您知道从您的文件和各个列获取行。因此,如果您有一些来自MODERATE列的值,您可以执行以下操作来“解包”列表:

import collections

from ast import literal_eval


def flatten(l):
    for el in l:
        if isinstance(el, collections.Iterable) and not isinstance(el, str):
            for sub in flatten(el):
                yield sub
        else:
            yield el


a_moderate_value = "[[[[1],None],None],None]"


a_list = literal_eval(a_moderate_value)

print(a_list)
# [[[[1], None], None], None]
# this is python list, i.e. not a string anymore 
# (I assume that all values can be parsed like this)

print(list(flatten(a_list)))
#[1, None, None, None]
# these individual values can be separated to different columns.

希望这会有所帮助。

答案 2 :(得分:0)

如果我理解你正在尝试做什么,请尝试制作一个列表来存储行,然后迭代第一个dict键和值,并在每个dict中为每个dict添加一个列表/元组。< / p>

这样的事情:

rows = []

for key, value in first_dict.items():
  rows.append([value, second_dict[key], third_dict[key], ...])

csv_writer.writerows(rows)