Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"DataFrame" object has no attribute 'reshape'

Tags:

python

pandas

csv

I want to reshape some data in a CSV file without header but I keep getting this error

AttributeError: 'DataFrame' object has no attribute 'reshape'

This is my script, I want to reshape the data in 2nd column only

import pandas as pd

df = pd.read_csv("test.csv", header=None, usecols=[1])

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

Here is the CSV

1,52.1
2,32.2
3,44.6
3,99.1
5,12.3
3,43.2
7,79.4
8,45.5
9,56.3
0,15.4
1,35.7
2,23.7
3,66.7
4,33.8
1,12.9
7,34.8
1,21.6
3,43.7
6,44.2
9,55.8

Output should be like this

[[  52.1   32.2   44.6   99.1  12.3]
 [  43.2   79.4   45.5   56.3   15.4]]
[[ 35.7  23.7  66.7  33.8  12.9]
 [ 34.8  21.6  43.7  44.2  55.8]]

Any ideas? Thank you

like image 715
Ling Avatar asked Feb 15 '17 03:02

Ling


1 Answers

pandas.dataframe doesn't have a built-in reshape method, but you can use .values to access the underlying numpy array object and call reshape on it:

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

#[[ 52.1  32.2  44.6  99.1  12.3]
# [ 43.2  79.4  45.5  56.3  15.4]]
#[[ 35.7  23.7  66.7  33.8  12.9]
# [ 34.8  21.6  43.7  44.2  55.8]]
like image 133
Psidom Avatar answered Sep 21 '22 15:09

Psidom