Python “DataFrame”对象没有属性“reshape”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42240376/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 21:27:58  来源:igfitidea点击:

"DataFrame" object has no attribute 'reshape'

pythoncsvpandas

提问by Ling

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

我想在没有标题的 CSV 文件中重塑一些数据,但我不断收到此错误

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

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

有任何想法吗?谢谢

回答by Psidom

pandas.dataframedoesn't have a built-in reshapemethod, but you can use .valuesto access the underlying numpy array object and call reshapeon it:

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