“DataFrame” object has no attribute 'reshape'

依然范特西╮ 提交于 2021-02-07 11:54:32

问题


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


回答1:


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


来源:https://stackoverflow.com/questions/42240376/dataframe-object-has-no-attribute-reshape

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!