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

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

Comments

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])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.