我想在没有标题的情况下重新设计一些数据,但我一直遇到此错误

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

这是我的脚本,我只想在第二列中重塑数据

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

这是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

输出应该像这样

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

有任何想法吗?谢谢

答案

pandas.dataframe没有内置reshape方法,但是您可以使用.values访问底层 numpy 数组对象并调用reshape在上面:

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

来自: stackoverflow.com