首页 > 解决方案 > 如何解决 AttributeError:'list' 对象没有属性 'shape'?

问题描述

此代码旨在根据某些条件将文件分成多个。

我在循环之前 print(temp.shape[0]) ,它可以工作。但它显示 n = temp.shape[0] AttributeError: 'list' object has no attribute 'shape' 在循环中。我想知道为什么会这样以及如何纠正它。

import pandas as pd

limit = 3
G0 = 7.75e-05
v=0.1           
step_size = 2e-3
splitcounts=200


data1 = pd.read_csv(\
    'C:\\Data Analysis\\Data.txt',\
    sep=',',names=['Time1','Current','Voltage','Distance', 'Time2'])

nrows1 = data1.shape[0]

temp=pd.DataFrame(columns=['Time','Current'])

print(temp.shape[0])#this is right when I run the code

for i,j in zip(range(0, int(nrows1)),range(0, int(splitcounts))):
  if 0<data1.at[i,'Current']<0.000075:
      temp=temp.append(data1.loc[i,0:2])
  else:
      n = temp.shape[0] #but it show 'AttributeError: 'list' object has no attribute 'shape'' 
      if n>5:
             temp.to_csv("C:\\Data Analysis\\Datas/%04d.csv" %j,\
                    sep=',',index=False, header=None)
      else:
          temp = []

标签: pythonpandas

解决方案


temp = pd.DataFrame(temp)
n = temp.shape[0]

添加这个可以将列表更改为数组。错误已解决,但我仍然无法将数据拆分为我需要的数据。然后我添加代码如下:

temp = temp.drop(index=temp.index)

它运作良好。整个正确的代码是:

for i in range(0, int(nrows1)):
     if 0<data1.at[i,'Current']<0.000075:
         temp = pd.DataFrame(temp)
         temp=temp.append(data1.iloc[i,0:2])
     else:
         #temp = np.array(list, dtype=float)
         temp = pd.DataFrame(temp)
         n = temp.shape[0]
         if n>20:
             #print(temp)
             temp.to_csv("C:/Datas/%04d.csv" %i,\
                     sep=',',index=False, header=None)
             temp = temp.drop(index=temp.index)
         else:
             temp = temp.drop(index=temp.index)

推荐阅读