我正在尝试从数据帧 df 计算 A 列和 B 列的分位数,但我想根据这些列的缺失值的百分比计算不同的分位数。
df = pd.DataFrame({'A': ['Bob', 'Jane', 'Alice', NA, NA, NA, 'Rob', 'Max'],
'B': ['Example', NA, NA, 'Test', 'Check', NA, NA, NA]})
另外,由于A和B是字符格式,所以我想先计算每列每行的长度,以便
df_count = pd.DataFrame({'A': [3, 4, 5, 0, 0, 0, 3, 3],
'B': [7, 0, 0, 4, 5, 0, 0, 0]})
然后根据缺失值的百分比计算 A 和 B 新值的分位数。
例如,如果 A 列的缺失值百分比大于 90%,那么我想计算分位数(0.99),否则如果 A 列的缺失值百分比小于 90%,我将计算分位数想计算分位数(0.10)。
作为最后一步,我将在新的数据框中写入分位数的值:
df_quant = pd.DataFrame({'A_quant': [quantile_value_for_A],
'B_quant': [quantile_value_for_B]})
有办法做到这一点吗?任何帮助将非常感激。
最佳答案
用途:
df = pd.DataFrame({'A': ['Bob', 'Jane', 'Alice', np.nan,np.nan, np.nan, 'Rob', 'Max'],
'B': ['Example', np.nan, np.nan, 'Test', 'Check', np.nan, np.nan, np.nan]})
df_count = pd.DataFrame({'A': [3, 4, 5, 0, 0, 0, 3, 3],
'B': [7, 0, 0, 4, 5, 0, 0, 0]})
<小时/>
#get percentage of NaNs
print (df.isna().mean())
A 0.375
B 0.625
dtype: float64
#compare by threshold, here 0.5 for test, with real data change to 0.9
thresh = .5
m = df.isna().mean() > thresh
print (m)
A False
B True
dtype: bool
#count both percentile
a = df_count.quantile(0.9999)
print (a)
A 4.9993
B 6.9986
Name: 0.9999, dtype: float64
b = df_count.quantile(0.999)
print (b)
A 4.993
B 6.986
Name: 0.999, dtype: float64
#set values by mask
out = np.where(m, a, b)
print (out)
[4.993 6.9986]
<小时/>
#create DataFrame
df_quant = pd.DataFrame([out], columns= m.index).add_suffix('_quant')
print (df_quant)
A_quant B_quant
0 4.993 6.9986
关于python - 如何根据缺失值的百分比计算数据框中列的不同分位数范围?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58590620/