python - 在 Pandas 中分配 NaN 不粘?
问题描述
我有一个值数据集,它们是 x、y、z 值(经度、纬度、海拔)。nan
我想通过公式扫描错误值来替换异常值。一切正常,除非我将值分配给它重置为原始值的数据框。感兴趣的函数是:
def removeOutliers(dataframe, header):
for ii in range(len(dataframe['Lng'])):
dataframe.reset_index(inplace=True, drop=True)
df_copy = dataframe.copy()
a = df_copy.iloc[ii]['Lng'] - df_copy.iloc[:]['Lng']
b = df_copy.iloc[ii]['Lat'] - df_copy.iloc[:]['Lat']
c = np.array((a**2 + b**2)**0.5 )
d = np.zeros((len(df_copy['Lng'])))
e = np.zeros((len(df_copy['Lng'])))
d[:] = df_copy.iloc[:]['Well']
e[:] = df_copy.iloc[:][header]
idx = np.argpartition(c, n_samples+1)
max_loc = np.where(e[idx[0:n_samples+1]] == e[ii])
neighbors = np.delete(e[idx[0:n_samples+1]], max_loc)
avg = np.mean((neighbors))
std = np.std(neighbors)
if ii==148:
print(df_copy.iloc[ii][header])
if df_copy.iloc[ii][header] > (avg + tolerance*std) or df_copy.iloc[ii][header] < (avg - tolerance*std):
df_copy.loc[ii, header] = np.nan
if ii==148:
print(df_copy.iloc[ii][header])
print(avg + tolerance*std)
print(avg - tolerance*std)
return df_copy
new_data = removeOutliers(data_by_zone, 'elevation')
目标是找到最接近的 20 个样本,计算均值和标准差。dev,如果参考样本大于avg+tolerance*std
(在这种情况下容差 = 1.5),则替换为 nan。这打印:
5223
nan #this is how I know my if statement is working
372
277
然后我运行 print(new_data.iloc[148]['elevation'])
我得到
5223
所以,就像它正在替换它,但是当我将它分配给 new_data 时,它会重置为原始值。我怎么做nan棒?如果它有所作为,那就是 python3.7 和 pandas0.25.1。注意:我只设置数据框的副本以避免 SettingWithCopy 警告...
更新:
我也尝试过使用df_copy.iloc[ii][header]
and df_copy.iloc[ii, df_copy.columns.get_loc(header)] = np.nan
,但没有运气
更新 2问题是由 for 循环内的数据框引起的。将其移至循环解决问题之前。
解决方案
推荐阅读
- mysql - 找不到驱动程序 (SQL: select * from `users`) (Lampp) (linux)
- python - 使用 python 数据框批量更新 postgres 表
- python - 如何在网站上执行 Python 函数?
- java - 为什么我的 bean 在测试期间没有自动装配?
- pm2 - 将每个目录请求指向 PM2 服务器上的 index.html
- html - 如何用 bootstrap 5 制作手风琴桌?
- python - 如何将 pytorch 模型转换为核心 ml 模型?
- java - 谓词问题“无效路径:'generatedAlias1.geometrie'”条件生成器
- python - csv文件中存在的重定向链接的解决方案
- javascript - 构造函数映射需要 Next js 中的“新”