用具有相似属性的项的平均值替换属性零值

2024-05-26 07:45:14 发布

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

我有一些在某些盆地的探测器的高度数据。零高度值是虚假的,我想用同一盆中探头的平均高度值来代替它们。你知道吗

import pandas as pd

index = [0,1,2,3,4,5]
s = pd.Series([0,2,2,0,1,6],index= index)  #height values
t = pd.Series(['A','A','A','B','B','B'],index= index)  #basins' names
df = pd.concat([s,t], axis=1, keys=['Height','Basin'])
print(df)

   Height Basin
0       0     A
1       2     A
2       2     A
3       0     B
4       1     B
5       6     B

我首先创建一个数据框来存储水池中的平均高度:

#find height avergage in same basin
bound_df = df[df['Height']>0]
mean_height_df = bound_df.groupby(['Basin'])['Height'].mean()
print(mean_height_df)

Basin
A    2.0
B    3.5

我试着用相应盆地的平均值来代替零值:

#substitute zeros w/ the average value
df.loc[df['Height']<=0, 'Height'] = mean_height_df.loc[mean_height_df['Basin'],'Height']

但这带来了一个我不明白的错误:

File "pandas/_libs/hashtable_class_helper.pxi", line 1218, in pandas._libs.hashtable.PyObjectHashTable.get_item

KeyError: 'Basin'

这是什么意思?是切片问题吗?你知道吗

有别的办法吗?你知道吗


Tags: 数据inpandasdfindex高度meanseries
1条回答
网友
1楼 · 发布于 2024-05-26 07:45:14

我觉得你想得太多了。尝试使用fillna,值是基于索引填充的。您需要一点设置,然后就可以像往常一样使用mean_height_df。你知道吗

# Set "Basin" as the index.
v = df.set_index('Basin')['Height']  
# Mask values that <= 0 and fill NaNs by the computed mean. 
df['Height'] = v.mask(v.le(0)).fillna(mean_height_df).values

相关问题 更多 >