'write only certain columns in output file

I have an array out, where for e.g., shape(out) is (1000,7), i.e. there are 1000 cities for which up to 7 temperatures can be reported, one for each day of the week. Depending on choices I do earlier in the code, I might decide to print in a csv file only temperatures for say Tue and Fri. How can I format my output in a clever way? At the moment I'm doing it in a loop.

E.g. all 7 days:

f.write('{},{:.1f},{:.1f},{:.1f},{:.1f},{:.1f},{:.1f},{:.1f}\n'.format(city[i],out[i,0],out[i,1],out[i,2],out[i,3],out[i,4],out[i,5],out[i,6]))

only Tue-Fri

f.write('{},{:.1f},{:.1f}\n'.format(city[i],out[i,1],out[i,4]))

etc ... for each possible combination. Obviously it's very inefficient an inelegant way of doing it. Any way I can make the write more flexible? Thanks!



Solution 1:[1]

Typically, you'd put the selected days in a variable and then build the resulting line dynamically.

You can create a list of values that should go into a line (city and temperatures), and then combine them with commas using str.join.

# all seven days
selected_days = [0, 1, 2, 3, 4, 5, 6]

# alternativeley, Tue and Fri
#selected_days = [1, 4]

f.write(','.join([city] + [str(out[i, day]) for day in selected_days])
f.write('\n')

(Let's not forget the trailing newline)

I've assumed city contains the city's name as a string and the temperatures are numeric values that need to be stringified.

Solution 2:[2]

Given that this is a numpy array, you might as well use numpy.savetxt() to do this for you:

import numpy as np
out = np.arange(7000).reshape((1000,7))
days = [0,2,4] # mon, wed, fri
np.savetxt('/path/to/file.csv', out[:, days], delimiter=',', fmt='%.1f')

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 MB-F
Solution 2