首页 > 解决方案 > 按熊猫中的许多列分组并将其添加到一个数据框中

问题描述

我有一个从 2018 年和 2019 年 stackoverflow 调查中制作的数据框。我有一列是这个特定受访者的薪水,我称之为“usd”和许多编程语言名称的列 - c、c++、c# 等 - 43其中,总共 44 列 - 1 是薪水,其他是编程语言。每行都有受访者的工资和他们使用的语言,如果他使用本列的语言,则为 1,否则为 0。现在,我想做的是为每种编程语言做一个 groupby 并获得工资的平均值 - usd 列的平均值,然后将其附加或合并或连接,这样我就有了每种编程语言的平均工资。如果您对如何实现这一目标有任何其他想法,我很乐意现在学习它,这就是我所拥有的:

y=pd.DataFrame( )
for x in df2.columns:
    if x!='usd':
        a=df2.groupby(x).mean()
        y=y.append(a)

这不是很神奇,因为如果我只是这样做 df2.groupby('C').mean()
df2.groupby('Python').mean()

然后它每次都会向我显示我拥有的编程语言名称,但我的 for 循环却没有,这实际上是我正在寻找的解决方案。

现在 df 看起来像这样:

usd        c python c# SQL c++ ruby ...etc..       
50000      1 0       1  1   0   1
100000     0 1       0  1   1   1
.
.
.
etc

and what i want to get is
     usd
c 
1    mean of usd columns for those with 1 under c column
0    mean of usd columns for those with 0 under c column
c++  
1    mean of usd columns for those with 1 under c++ column
0    mean of usd columns for those with 0 under c++ column
.
.
.
.

谢谢!

谢谢!!

标签: pandas

解决方案


给你..你必须按语言列值对它们进行分组,并取'usd'列的平均值

样本数据集:

 usd  java  python  c
0   10     1       0  1
1   20     0       1  1
2   30     1       1  0
3   40     0       0  1
4   50     1       1  0

代码

for lang in df.columns[1:]:
    print(df.groupby(lang)['usd'].mean())

结果

java
0    30
1    30

python
0    25.000000
1    33.333333

c
0    40.000000
1    23.333333

您可以将结果合并/合并到一个 df 中。

代码

for lang in df.columns[1:]:
    group_lang = (df.groupby(lang)['usd'].mean().reset_index())
    group_lang['lang'] = lang
    df2 = pd.concat([df2, group_lang[['lang','usd']]])

df2=df2.reset_index().set_index('lang').rename(columns={'index':'val'})
print(df2)

结果:

        val        usd
lang                  
java      0  30.000000
java      1  30.000000
python    0  25.000000
python    1  33.333333
c         0  40.000000
c         1  23.333333

可能有更好的解决方案,但这应该可行。让我知道事情的后续。干杯:)


推荐阅读