【问题标题】:redistribute data in Gaussian distribution with pd.DataFrame使用 pd.DataFrame 以高斯分布重新分配数据
【发布时间】:2018-11-25 05:49:20
【问题描述】:

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

【问题讨论】:

  • 您想修改每一行中的此类概率,以重现更像高斯的分布吗?
  • @GianfrancescoAngelini 是的,我想修改这种分布中的每一行。

标签: python python-3.x pandas numpy normal-distribution


【解决方案1】:

如果您想重现更类似于高斯的分布,您所说的是单点加权(连续班级得分)。
所以我建议使用高斯分布权重来放大分数。
这里是一个例子:

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)

【讨论】:

  • 感谢您的回答!顺便说一句,如何调整此代码中分布的平均值?
  • 您想调整单行均值,使每一行都与其他行不同,还是要获得所有行的唯一均值?
  • 我需要一个唯一的所有行的平均值。谢谢。
猜你喜欢
  • 1970-01-01
  • 2012-09-12
  • 1970-01-01
  • 2017-11-24
  • 2019-07-15
  • 1970-01-01
  • 2015-10-10
  • 2015-12-28
  • 2012-10-08
相关资源
最近更新 更多