0

My writer function looks like:

with open(filename, "w") as file:
    file.truncate(0)
    writer = csv.writer(file)
    writer.writerows(input_list)

My input_list looks like:

[[10.0, 11.0, 20.0, 20.0, 0.8], [40.0, 42.0, 20.0, 20.0, 0.6]]

My output csv file looks like:

10.0,11.0,20.0,20.0,0.8
40.0,42.0,20.0,20.0,0.6

I want it to look like:

10, 11, 20, 20, 0.8
40, 42, 20, 20, 0.6

I would like the formatting of the spaces after the numbers themselves. While I could add something within the program to create a space between the elements and check for whether the number is less than 1, before casting it to an int (numbers above 1 cannot be floats), I would like to look for a more pythonic and elegant solution.

SDG
  • 2,260
  • 8
  • 35
  • 77
  • “0.6” has only one significant digit as mathematicians define the term. What output do you want for 0, 123, and 0.123, or values like those never occur? – Eric Postpischil Jun 18 '19 at 10:50
  • @EricPostpischil 0 and 123 can occur, but 0.123 can never occur. I would like to represent those two as 0 and 123 – SDG Jun 19 '19 at 01:28

2 Answers2

1
>>> from math import log10, floor
>>> def round_to_1(x):
...   return round(x, -int(floor(log10(abs(x)))))

Loop through your elements and apply this function before writing to a csv. Laborious but should work.

Jkind9
  • 742
  • 7
  • 24
  • is there a way we can map this to each and every element within the list of lists, all in the same line as the line as the csv_writer? Maybe a map function? – SDG Jun 18 '19 at 10:42
  • Just use a double loop. For line in list: For item in line. – Jkind9 Jun 18 '19 at 10:44
  • https://stackoverflow.com/questions/25082410/apply-function-to-each-element-of-a-list – Jkind9 Jun 18 '19 at 10:46
-1

You can use pandas library for this.

=^..^=

import pandas as pd

data = [[10.0, 11.0, 20.0, 20.0, 0.8], [40.0, 42.0, 20.0, 20.0, 0.6]]

df = pd.DataFrame(data)
# convert values to int
df[0] = df[0].astype(int)
df[1] = df[1].astype(int)
df[2] = df[2].astype(int)
df[3] = df[3].astype(int)

# save data frame
df.to_csv('data.csv')

Output:

    0   1   2   3    4
0  10  11  20  20  0.8
1  40  42  20  20  0.6
Zaraki Kenpachi
  • 5,510
  • 2
  • 15
  • 38