繁体   English   中英

Python如何格式化CSV文件写入

[英]Python How To Format CSV File Write

这是我的问题的图像: 问题的形象

如何将方括号从CSV文件中格式化,以及如何将CSV中的值分别保留在其他列的“中等”类别中?

这是涉及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())

您可以使用Pandas来做到这一点。

import pandas as pd

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

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

我假设您知道谁从文件中获取行以及各个列。 因此,如果您在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.

希望这可以帮助。

如果我正确理解了您要执行的操作,请尝试创建一个列表来存储行,然后遍历第一个字典键和值,并在列表/元组中附加当前字典的每个字典中的值。

像这样:

rows = []

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

csv_writer.writerows(rows)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM