python - 为什么在这种情况下,pandas 中 .mean() 方法的轴是相反的?
问题描述
我有一个数据框,height_df
,具有三个测量值,'height_1','height_2','height_3'
。我想创建一个具有所有三个高度平均值的新列。打印输出height_df
如下
height_1 height_2 height_3
0 1.78 1.80 1.80
1 1.70 1.70 1.69
2 1.74 1.75 1.73
3 1.66 1.68 1.67
以下代码有效,但我不明白为什么
height_df['height'] = height_df[['height_1','height_2','height_3']].mean(axis=1)
我实际上想要跨行轴的平均值,即为每一行计算三个高度的平均值。那时我会认为 mean 中的轴参数应该设置为 0,因为这对应于跨行应用平均值,但是 axis=1 是我正在寻找的结果。为什么是这样?如果axis=1
是列和axis=0
行,那么为什么要跨行.mean(axis=1)
取平均值?
解决方案
只需要告诉意味着跨列工作axis=1
df = pd.DataFrame({"height_1":[1.78,1.7,1.74,1.66],"height_2":[1.8,1.7,1.75,1.68],"height_3":[1.8,1.69,1.73,1.67]})
df = df.assign(height_mean=df.mean(axis=1))
df = df.assign(height_mean=df.loc[:,['height_1','height_2','height_3']].mean(axis=1))
print(df.to_string(index=False))
输出
height_1 height_2 height_3 height_mean
1.78 1.80 1.80 1.793333
1.70 1.70 1.69 1.696667
1.74 1.75 1.73 1.740000
1.66 1.68 1.67 1.670000
推荐阅读
- android - Android NDK:在 android_main 函数中处理和创建输入事件
- nodemailer - 如何使用 nodemailer 发送 html 模板?
- node.js - 创建离子应用程序时无法解析依赖树
- arrays - 程序警告中的gettinan错误:函数'Binsearch'的隐式声明[-Wimplicit-function-declaration] res = Binsearch(arr,n-1,0,x);
- azure-servicebus-queues - Azure ServiceBus - 提供的锁无效
- node.js - 我需要让 Ionic 和 Vue 一起工作
- javascript - 错误:无法在视图目录中查找视图“/listings”
- c++ - 是什么导致 leetcode #695 Max Area Island 溢出
- ruby-on-rails - Bundler 在任何资源中都找不到 rake
- python - 如何在游戏奥赛罗(黑白棋)中实现由可能的动作组成的树