使用 pd.DataFrame 重新分布高斯分布中的数据

redistribute data in Gaussian distribution with pd.DataFrame

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

如果你想重现更像高斯的分布,你正在谈论单点的权重(class 连续得分)。
所以我建议使用高斯分布式权重来放大分数。
举个例子:

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

这意味着在上面的主要例子中,在 df.iloc[nr] 中替换 aw 之前你应该做

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