首页 > 解决方案 > 使用 pd.DataFrame 以高斯分布重新分配数据

问题描述

我有一个 pandas DataFrame,其中包含属于每个类(列)的每个样本的概率。碰巧的是,几乎 99% 的类都有< 0.01概率,而很少有> 0.5概率。出于某种原因,我希望概率分布在 和 之间的高斯分布01。我想平均值应该0.5在这种情况下,但如果可能的话,我也希望能够修改这种分布的平均值。我希望对每一行分别进行此操作,如何使用 pandas 数据框来执行此操作?

标签: pythonpython-3.xpandasnumpynormal-distribution

解决方案


如果你想重现一个更像高斯的分布,你正在谈论单点的加权(连续的班级分数)。
所以我建议使用高斯分布权重来放大分数。
这里有一个例子:

import numpy as np
import pandas as pd
#Preparation of the data
nclasses = 10
nsamples = 5
df_c = []
for nc in range( nsamples ):
    a = np.random.rand(nclasses)
    a = [n/np.sum(a) for n in a]
    df_c.append( a )

df = pd.DataFrame(df_c)

# Now let's weight

for nr in range( df[0].count() ): #iterate over rows
    a = df.iloc[nr] #capture the nth row
    #generate Gaussian weights
    gw = np.random.normal( np.mean(a), np.std(a), len(a) )
    #sort gw and a in order to assign one to the other
    gw = np.sort(gw)
    b_ind = np.argsort(a) #indexes to sort a
    b = a[b_ind]          #sorted version of a
    # now weight the row
    aw_r = a*b # you can reduce the entity adding anotherfactor, like 0.8 for instance
    # back from sort
    aw = [ aw_r[n] for n in b_ind ]
    #update the dataframe
    df.iloc[nr] = aw

# there you go!

希望它会有所帮助

更新__
如果要将每行的平均值调整为相同的值,例如 0.5,则只需减去行平均值和目标平均值之间的差值(在本例中为 0.5)。

a=np.array([1,2,3,47,2,6])
print( a.mean() ) # 10.1666
target_mean = 0.5

a_adj = a-(np.mean(a) - target_mean)
print( np.mean( a_adj ) ) # 0.5

这意味着在上面的主要示例中,在将 aw 替换为 df.iloc[nr] 之前,您应该这样做

aw = aw-(np.mean(aw) - 0.5)

推荐阅读