首页 > 解决方案 > 您如何确定每个变量的最佳公司并复制案例?

问题描述

我想比较子组的平均值。应将具有最低和最高均值的子组的案例复制并应用于数据集的末尾:

Input
df.head(10)

Outcome
Company     Satisfaction    Image   Forecast    Contact
0   Blue    2   3   3   1
1   Blue    2   1   3   2
2   Yellow  4   3   3   3
3   Yellow  3   4   3   2
4   Yellow  4   2   1   5
5   Blue    1   5   1   2
6   Blue    4   2   4   3
7   Yellow  5   4   1   5
8   Red     3   1   2   2
9   Red     1   1   1   2

我的样本中有大约 100 个案例。现在我看看每家公司的手段。

Input
df.groupby(['Company']).mean()

Outcome     
        Satisfaction    Image   Forecast    Contact
Company                 
Blue    2.666667    2.583333    2.916667    2.750000
Green   3.095238    3.095238    3.476190    3.142857
Orange  3.125000    2.916667    3.416667    2.625000
Red     3.066667    2.800000    2.866667    3.066667
Yellow  3.857143    3.142857    3.000000    2.714286

因此,为了满意,黄色获得了最好的价值,而蓝色获得了最差的价值。我想复制黄色和蓝色的案例并将它们添加到数据集中,但现在使用新标签“最佳”和“最差”。我不想重命名它,我也想迭代数据集和其他列(例如图像)。有解决办法吗?添加案例后,我想要这样的输出:

Input
df.groupby(['Company']).mean()

Expected Outcome    
        Satisfaction    Image   Forecast    Contact
Company                 
Blue    2.666667    2.583333    2.916667    2.750000
Green   3.095238    3.095238    3.476190    3.142857
Orange  3.125000    2.916667    3.416667    2.625000
Red     3.066667    2.800000    2.866667    3.066667
Yellow  3.857143    3.142857    3.000000    2.714286
Best    3.857143    3.142857    3.000000    3.142857
Worst   2.666667    2.583333    2.866667    2.625000

但我怎么说。将再次添加每列具有最佳和最差值的公司,而不仅仅是重命名,因为我想用另一个软件进一步处理数据,这一点非常重要。

************************更新************************* ***

我发现了如何复制正确的案例:

Input
df2 = df.loc[df['Company'] == 'Yellow']
df2 = df2.replace('Yellow','Best')
df2 = df2[['Company','Satisfaction']]
new = [df,df2]
result = pd.concat(new)
result

Output
    Company     Contact     Forecast    Image   Satisfaction
0   Blue    1.0     3.0     3.0     2
1   Blue    2.0     3.0     1.0     2
2   Yellow  3.0     3.0     3.0     4
3   Yellow  2.0     3.0     4.0     3
..........................................
87  Best    NaN     NaN     NaN     3
90  Best    NaN     NaN     NaN     4
99  Best    NaN     NaN     NaN     1
111     Best    NaN     NaN     NaN     2

现在,我也想复制其他变量具有最佳值的公司案例。但现在我必须手动确定哪个公司最适合每个类别。没有更舒适的解决方案吗?

标签: python-3.xpandas

解决方案


我有一个解决方案。首先,我创建一个字典,其中包含我想创建一个最好和最坏的虚拟公司的变量:

variables = ['Contact','Forecast','Satisfaction','Image']

在我遍历这些列并使用新标签“Best”或“Worst”再次添加案例后:

for n in range(0,len(variables),1):
    Start = variables[n-1]
    neu = df.groupby(['Company'], as_index=False)[Start].mean()
    Best = neu['Company'].loc[neu[Start].idxmax()]
    Worst = neu['Company'].loc[neu[Start].idxmin()]
    dfBest = df.loc[df['Company'] == Best]
    dfWorst = df.loc[df['Company'] == Worst]
    dfBest = dfBest.replace(Best,'Best')
    dfWorst = dfWorst.replace(Worst,'Worst')
    dfBest = dfBest[['Company',Start]]
    dfWorst = dfWorst[['Company',Start]]
    new = [df,dfBest,dfWorst]
    df = pd.concat(new)

多谢你们 :)


推荐阅读