0

I found this question : How to reshape every nth row's data using pandas?

I modified the script to save the result in csv file but there is an error saying

AttributeError: 'numpy.ndarray' object has no attribute 'to_csv'

This is the script. Basically I just added

to_csv()

to it.

import pandas as pd

df = pd.read_csv("test.csv")

start = 0
for i in range(0, len(df.index)):
    if (i + 1)%10 == 0:
        result = df['Break'].iloc[start:i+1].reshape(2,5)
        start = i + 1

        result.to_csv('testing.csv')

My question is that is it possible to save the result like this

[['ww' 'ee' 'qq' 'xx' 'dd']
 ['gg' 'hh' 'tt' 'yy' 'uu']]
[['ii' 'oo' 'pp' 'mm' 'ww']
 ['zz' 'cc' 'rr' 'tt' 'll']] 

as csv file?

From what I see from the result, 'ww' until 'uu' (the first matrix) can be considered as 1st row while the second matrix ('ii' until 'll') can be considered as 2nd row and this could be export as csv file (or maybe in other file format; h5 or text)

Thank you for your help.

[UPDATE]

I already looked at the possible duplicate question but I think mine a little bit different since the other question showed the output to be something like this

[ 266.77832991  201.06347505  446.00066136  499.76736079  295.15519906
  214.50514991  422.1043505   531.13126879  287.68760191  201.06347505
  402.68859792  478.85808879  286.19408248  192.10235848]

while mine is like this

[['ww' 'ee' 'qq' 'xx' 'dd']
 ['gg' 'hh' 'tt' 'yy' 'uu']]
[['ii' 'oo' 'pp' 'mm' 'ww']
 ['zz' 'cc' 'rr' 'tt' 'll']]

I also tried the answer provided there but there is error. Here is what I tried

import pandas as pd
import numpy as np

df = pd.read_csv("test.csv")

start = 0
for i in range(0, len(df.index)):
    if (i + 1)%10 == 0:
        result = df['Break'].iloc[start:i+1].reshape(2,5)
        start = i + 1
        save = np.savetxt('testing.csv', result, delimiter=' , ')

and the error

TypeError: Mismatch between array dtype ('object') and format specifier ('%.18e , %.18e , %.18e , %.18e , %.18e')
Community
  • 1
  • 1
Fang
  • 754
  • 1
  • 11
  • 29
  • Possible duplicate of [Saving prediction results to CSV](http://stackoverflow.com/questions/34864695/saving-prediction-results-to-csv) – Vaishali Feb 10 '17 at 04:35
  • thank you @VaishaliGarg I already looked a that question but I think mine a little bit different. I already updated my question to reflect on this. – Fang Feb 10 '17 at 04:57

1 Answers1

0

Given a numpy array like this

a = np.asarray([ [1,2,3], [4,5,6], [7,8,9] ])

You can save it as csv file like this

numpy.savetxt("foo.csv", a, delimiter=",")

The resulting file foo.csv has the desired format.

Its answered here

Community
  • 1
  • 1
Vaishali
  • 32,439
  • 4
  • 39
  • 71