[英]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.