简体   繁体   中英

Python How To Format CSV File Write

This is an image of my problem: 问题的形象

How do I format the brackets out of the CSV file and also how do I seperate the values in the CSV all stuck in the "MODERATE" category in the other columns?

Here is the part of code which involves the CSV writing.

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())

You can use Pandas to do it.

import pandas as pd

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

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

I assume you know who to get lines from your file, and individual columns. Thus, if you have some value from MODERATE column, you could do as follows to "unwrap" the lists:

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.

Hope this helps.

If I understand correctly what you are trying to do, try making a list to store the rows and then iterating over the first dict keys and values and appending a list/tuple with the values in each dict for the current key.

Something like this:

rows = []

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

csv_writer.writerows(rows)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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