Reputation: 2167
I am writing my df
to a .csv
file to load into Minitab. However, I am currently doing a lot of post-manipulation of the .csv
file in order to make it friendly for Minitab. I would like to write my Python code to make it easier and quicker for me to already have it in the desired format.
Currently: csv.writer
is currently writing the .csv
to the following format:
My objective: is to write the csv in this format; (and to also change the periods to commas).
import csv
a_file = open("raw_data.csv", "w")
writer = csv.writer(a_file)
for key, value in df.items():
writer.writerow([key, value])
a_file.close()
My df
looks like the following:
{'K': [77.92589285714281, 75.34811320754717, 77.68070175438596, 75.37850467289722, 79.62212389380527, 79.40999999999998, 79.3535714285714, 77.35833333333332, 79.21904761904761, 'Z': [76.04260869565215, 80.10176991150445, 76.62086956521739, 77.64473684210527, 79.50087719298244, 80.70350877192982, 78.92543859649123, 80.88198198198197, 78.96869565217392, 77.112389380531,}
Upvotes: 0
Views: 37
Reputation: 78
Since you have all the values inside the key, you have to iterate again the values. The code you must need looks like this:
import csv
a_file = open("raw_data.csv", "w")
writer = csv.writer(a_file, quoting=csv.QUOTE_ALL)
for key, values in df.items():
for value in values:
writer.writerow([key, str(value).replace(".",",")])
The quoting
dialet close all the values and keys in doublequotes, since you will use commas in the values you will need it(since the csv format works with commas), and the str(value).replace(".",",")
just replace the periods with commas
Upvotes: 1
Reputation: 10389
you are very close
import csv
a_file = open("raw_data.csv", "w")
writer = csv.writer(a_file)
for key, value in df.items():
# value is a list, so you have to iterate through that
for v in value:
# you'd see this fix in a moment on your own
writer.writerow([value, key])
a_file.close()
I don't know how to do the decimal conversion off the top of my head, I'm sure it's "locale" related.
Upvotes: 2