pandas - 按熊猫中的许多列分组并将其添加到一个数据框中
问题描述
我有一个从 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
.
.
.
.
谢谢!
谢谢!!
解决方案
给你..你必须按语言列值对它们进行分组,并取'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
可能有更好的解决方案,但这应该可行。让我知道事情的后续。干杯:)
推荐阅读
- swift - 如何在我的 NATIVESCRIPT PROJECT 中更改/添加 swift 版本?
- java - 在 IntelliJ 2020 1.1 中创建新 servlet 后无法解决符号“servlet”错误
- php - 评论相互重叠
- jquery - eonasdan bootstrap datetimepicker minDate 过去的一些日期除外
- c# - c#中的'is {}'语法是什么意思?
- javascript - 无法更改我的 react-native-datepicker 上的语言
- postgresql - 试图创建一个新的 Postgres 连接
- javascript - 为什么这个 Redux 状态会发生变异?
- npm - 为什么我需要与 react-redux 一起安装 redux?
- .htaccess - 有条件地在 .htaccess 中设置 Files 指令