1

The test3.csv includes one column with 33 numbers. I would like to reshape the one column to 11 rows and 3 columns. And then, I want to save as new ascii file with the rows and columns like attached image.

First try:

import csv
f = open('test3.csv')
csv_f = csv.reader(f)
for row in csv_f:
    print row /* The result is 

The result is:

['0.000016'] ['0.000045'] ['0.000062'] ['0.000063'] ['0.000063'] ['0.000063']... **[' ']** means string?

Second try:

f = open('test3.csv')
csv_f = csv.reader(f)
for row in csv_f:
    print row[0]

The result is:

0.000016 0.000045 0.000062 0.000063 0.000063 0.000063 ...I think they are number.

Third try:

import csv
import numpy as np
f = open('test3.csv')
csv_f = csv.reader(f) 
a1 = [] 
for row in csv_f:
    a1.append(row[0])
print a1

The result is:

['0.000016', '0.000045', '0.000062', '0.000063', '0.000063', '0.000063',...].

Actually I want to this result as ascii file like:

Image

Stephen Rauch
  • 47,830
  • 31
  • 106
  • 135

2 Answers2

0

Here is some code which will do what you need:

Code:

import csv

# read each line of the input csv
with open('file3') as f:
    csv_f = csv.reader(f)

    # convert the first element of each line to a formated float
    numbers = ['%.6f' % float(row[0]) for row in csv_f]

# make sure the length is divisible by 3
numbers += [''] * (-len(numbers) % 3)

# reorder to by 3
numbers = [(numbers[i], numbers[i+1], numbers[i+2])
           for i in range(0, len(numbers), 3)]

# print each line
for line in numbers:
    print(' '.join(line))

Test data:

0.000016
0.000045
0.000062
0.000063
0.000063
0.000063
0.000079
0.000078
0.000045
0.000062
0.000062
0.000062
0.000062
0.000062
0.000062
0.000077
0.000073
0.000062
0.000062
0.000045
0.000063

Result:

0.000016 0.000045 0.000062
0.000063 0.000063 0.000063
0.000079 0.000078 0.000045
0.000062 0.000062 0.000062
0.000062 0.000062 0.000062
0.000077 0.000073 0.000062
0.000062 0.000045 0.000063
Stephen Rauch
  • 47,830
  • 31
  • 106
  • 135
0

I leveraged this great answer:

from itertools import izip_longest

def grouper(iterable, n, fillvalue=None):
    args = [iter(iterable)] * n
    return izip_longest(*args, fillvalue=fillvalue)

with open('data.txt', 'r') as f:
    for group in grouper(f, 3, ''):
        print ' '.join([x.strip() for x in group])
Community
  • 1
  • 1
DevLounge
  • 8,313
  • 3
  • 31
  • 44