如何解决AttributeError:“list”对象没有属性“shape”?

2024-09-30 03:24:30 发布

您现在位置:Python中文网/ 问答频道 /正文

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

我在循环之前打印(临时形状[0]),它可以工作。但它显示n=温度形状[0] AttributeError:“list”对象在循环中没有属性“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 = []

Tags: csvdatarangeanalysiscurrenttempseplist
2条回答

错误出现在代码的最后一行:

temp=[]

在这一行中,您通过创建一个新的空列表将temp转换为一个列表。相反,您应该使用以下方法创建一个空的DataFrame

temp=pd.DataFrame()

旁注:

使用append方法时,不需要进行属性设置。您正在这样做:

temp=temp.append(data1.loc[i,0:2])

相反,请删除属性并仅使用以下内容:

temp.append(data1.loc[i,0:2])

通常,append方法在不创建新实例的情况下向集合添加新条目

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)

相关问题 更多 >

    热门问题