2017-02-15 77 views
3

我想在没有头的CSV文件重塑了一些数据,但我不断收到此错误“数据帧”对象有没有属性“重塑”

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

这是我的剧本,我要重塑数据第2列只有

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

任何想法?谢谢

+0

它看起来像你正在寻找堆叠的数据,所以你可能想看看熊猫的数据透视方法。它适用于您的数据,但会导致索引具有太多重复值,因此它不会提供您正在搜索的解决方案。 – RexFuzzle

+0

左侧不是索引。它实际上是第一列的数据。 @Psidom的答案就是我想要做的。顺便说一句,谢谢你的建议。 =) – Ling

回答

4

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

谢谢你的帮助。有效!在此之前我不知道'.values' – Ling