python-3.x - 在 pandas Dataframe 上获取具有多个条件(按列)的平均值
问题描述
我最近开始使用熊猫,但找不到答案。(也许只是因为我不知道要搜索的查询词)
这是示例代码
test1 = {'col1' : ["A","A","A","A","B","B","B","B"],
'col2' : ["C","D","C","D","C","D","C","D"],
'year' :["2012","2012","2013","2013","2012","2012","2013","2013"],
'value' : [3,4,25,1,3,2,1,3]}
df_t = pd.DataFrame(data=test1)
df_t
在这个 DataFrame 中,我想在某些条件下计算值的平均值。col1 和 col2 应该耦合(因为它是贸易数据),所以我想要得到的是
Mean value of years of 'A(col1)', 'C(col2)'
Mean value of years of 'A', 'D'
Mean value of years of 'B', 'C'
...
etc.
因此,我想要一个带有 'col1'、'col2'、'mean_value' 列的新 DataFrame。但我想如果有人教我如何在上述条件下获得平均值,我可以处理它。
如果有人能启发我,那将不胜感激。
感谢您的兴趣!
有一个美好的一天。
解决方案
尝试df_t.groupby(['col1', 'col2'])['value'].mean().reset_index()
col1 col2 value
0 A C 14.0
1 A D 2.5
2 B C 2.0
3 B D 2.5
推荐阅读
- .htaccess - htaccess 允许具有不同方案的 Origin 多个域
- ios - 为什么 Swift AVAudioPlayer 在 MPRemoteCommandCenter 播放命令后不改变状态?
- linux - 如何使版本排序命令在 sh 文件中工作?
- python - 是否使用 numpy 的 dot 或 matmul 函数
- c# - 如何在 C# 中将 System.Drawing.Color 转换为 ClosedXML.Excel.XLColor
- laravel - Laravel Passport Oauth 自定义页面/自动重定向
- html - 如何使用仅使用 CSS flexbox 的放大字体将导航栏从侧面重新定位到中心?
- loops - 为什么我不能在两个不同的映射函数中可变地借用一个变量?
- javascript - D3.js v5 圆群图调整力以考虑可变大小的半径
- r - For 循环不使用 print() 函数返回任何值