0

I have a .CSV file named TEMP2.csv which contains the following:

1376460059,4,33.29,33.23,33.23,33.29,33.23,33.29,33.29,33.29,33.33,33.29,33.33,33.29,33.33,33.33,33.37,33.33,33.33,33.33,33.33,33.37,33.37,33.37,33.37

This is how I am reading the file:

import csv
import numpy as np

data = np.genfromtxt('TEMP2.csv',delimiter=',', skip_header=2)

After skipping the fisrt two number I need to add the next 4 numbers to a first row in a matrix. The next 4 to the second row in the same matrix and so on.

However that is just not working, I am really new to python been trying for some days and still I do not get the results. I will apreciate your help so much. Thanks.

Cristian J Estrada
  • 357
  • 2
  • 3
  • 14

1 Answers1

0

Maybe you need reshape.And add zero to the end of array if it can't reshape.

COLUMN_NUM = 4
data = np.genfromtxt('a.csv', delimiter=',')[2:]

if data.shape[0] % 4 == 0:
    print data.reshape((-1, 4))
else:
    data = np.pad(data, (0, COLUMN_NUM - len(data) % COLUMN_NUM), 'constant')
    print data.reshape((-1, COLUMN_NUM))

The new shape should be compatible with the original shape. So it reshape successfully,you will get this result:

[[ 33.29  33.23  33.23  33.29]
 [ 33.23  33.29  33.29  33.29]
 [ 33.33  33.29  33.33  33.29]
 [ 33.33  33.33  33.37  33.33]
 [ 33.33  33.33  33.33  33.37]
 [ 33.37  33.37  33.37  33.11]]

Hope this helps.

McGrady
  • 10,869
  • 13
  • 47
  • 69
  • That sure help me a lot @McGrady. Could you now please help me here: That first number it's a Unix Timestamp. The second its the frecuency the rest number where generated. What would be the best way to know the time they were generated? – Cristian J Estrada Feb 20 '17 at 06:25
  • @CristianJEstrada Have a look at [Converting unix timestamp string to readable date](http://stackoverflow.com/questions/3682748/converting-unix-timestamp-string-to-readable-date-in-python) – McGrady Feb 20 '17 at 06:29
  • I will, also I tried to getting the mean out of the first row but instead it will give me the mean out of everthing. – Cristian J Estrada Feb 20 '17 at 06:35
  • @CristianJEstrada You'd better ask another question, – McGrady Feb 20 '17 at 06:39
  • I was able to do it: for x in range(0, len(data)): xtime = ((x*1.)/COLUMN_NUM) + 1376460059 xtime = np.array(xtime) print xtime Do you know how to append my results to the matrix you have showed me before? – Cristian J Estrada Feb 20 '17 at 08:27