用pandas函数代替该函数:def NaND(): data=data2[['speed_391_24','speed_391_23','speed_391_22']] for i in x_index: data.loc[i,'speed_391_24']=np.nan data.loc[i,'speed_391_23']=np.nan data.loc[i,'speed_391_22']=np.nan return data
时间: 2023-06-10 12:02:33 浏览: 37
你可以使用pandas的fillna函数来代替该函数。具体代码如下:
data = data2[['speed_391_24', 'speed_391_23', 'speed_391_22']]
data = data.fillna(value=np.nan)
return data
相关问题
用pandas函数代替下列语句:def NaND(): data=data2[['speed_391_24','speed_391_23','speed_391_22']] for i in x_index: data.loc[i,'speed_391_24']=np.nan data.loc[i,'speed_391_23']=np.nan data.loc[i,'speed_391_22']=np.nan return datadata2_0=NaND() nan_index=[] for i in range(len(data2_0)): if (np.isnan(data2_0.iat[i,0])==True): nan_index.append(i)
你可以使用pandas的fillna函数来实现这个功能,具体的代码如下所示:
data = data2[['speed_391_24','speed_391_23','speed_391_22']]
data = data.fillna(np.nan)
data2_0 = data
nan_index = []
for i in range(len(data2_0)):
if (np.isnan(data2_0.iat[i,0])==True):
nan_index.append(i)
希望能够帮到你!
用pandas函数代替下列语句:for i in range(len(data2_0_time3)): if (np.isnan(data2_0_time3.iat[i,0])==True): if 3<=i<=len(data2_0_time3)-4: data2_0_time3.loc[i,'speed_391_24']=0 data2_0_time3.loc[i,'speed_391_23']=0 data2_0_time3.loc[i,'speed_391_22']=0 k=0 for j in range(1,4): if np.isnan(data2_0_time3.iat[i-j,0])==False: data2_0_time3.loc[i,'speed_391_24']=data2_0_time3.iat[i,0]+data2_0_time3.iat[i-j,0] data2_0_time3.loc[i,'speed_391_23']=data2_0_time3.iat[i,1]+data2_0_time3.iat[i-j,1] data2_0_time3.loc[i,'speed_391_22']=data2_0_time3.iat[i,2]+data2_0_time3.iat[i-j,2] k=k+1 if np.isnan(data2_0_time3.iat[i+j,0])==False: data2_0_time3.loc[i,'speed_391_24']=data2_0_time3.iat[i,0]+data2_0_time3.iat[i+j,0] data2_0_time3.loc[i,'speed_391_23']=data2_0_time3.iat[i,1]+data2_0_time3.iat[i+j,1] data2_0_time3.loc[i,'speed_391_22']=data2_0_time3.iat[i,2]+data2_0_time3.iat[i+j,2] k=k+1 data2_0_time3.loc[i,'speed_391_24']=data2_0_time3.iat[i,0]/k data2_0_time3.loc[i,'speed_391_23']=data2_0_time3.iat[i,1]/k data2_0_time3.loc[i,'speed_391_22']=data2_0_time3.iat[i,2]/k
可以使用下列代码代替原始的for循环代码:
```python
mask = np.isnan(data2_0_time3.iloc[:, 0])
mask[3:-4] &= True
for i in range(1, 4):
mask[3:-4] &= ~np.isnan(data2_0_time3.iloc[:, i])
data2_0_time3.loc[mask, 'speed_391_24'] = data2_0_time3.loc[mask, 0]
data2_0_time3.loc[mask, 'speed_391_23'] = data2_0_time3.loc[mask, 1]
data2_0_time3.loc[mask, 'speed_391_22'] = data2_0_time3.loc[mask, 2]
for i in range(1, 4):
data2_0_time3.loc[mask, 'speed_391_24'] += data2_0_time3.shift(-i)[mask][0]
data2_0_time3.loc[mask, 'speed_391_23'] += data2_0_time3.shift(-i)[mask][1]
data2_0_time3.loc[mask, 'speed_391_22'] += data2_0_time3.shift(-i)[mask][2]
data2_0_time3.loc[mask, 'speed_391_24'] /= (k + i)
data2_0_time3.loc[mask, 'speed_391_23'] /= (k + i)
data2_0_time3.loc[mask, 'speed_391_22'] /= (k + i)
```
此代码将创建一个掩码(即一个布尔数组),以标识哪些行需要更新“speed_391_XX”列。接下来,通过使用函数`shift`和`loc`将该列中的值从相邻的3行中收集到目标行。最后,它更新列的平均值为除以观察到的非空值数量。
阅读全文