简体   繁体   中英

Is it possible to save/export a reshaped data using pandas into csv/text/h5 file?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM