对于如何定义python轴,以及它们是否引用DataFrame的行或列,我一直感到困惑。考虑下面的代码:
df = pd.DataFrame([[1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 3]], columns=["col1", "col2", "col3", "col4"]) df col1 col2 col3 col4 0 1 1 1 1 1 2 2 2 2 2 3 3 3 3 因此,如果调用df.mean(axis=1),我们将在各行中获得均值:
df.mean(axis=1) 0 1 1 2 2 3 但是,如果调用df.drop(name, axis=1),则实际上是删除一列,而不是一行:
df.drop("col4", axis=1) col1 col2 col3 0 1 1 1 1 2 2 2 2 3 3 3 有人可以帮助我了解pandas / numpy / scipy中“轴”的含义吗?
旁注,DataFrame.mean可能只是定义错误。它在文档中DataFrame.mean说这axis=1应该是指各列的平均值,而不是各行的平均值。 问题来源于stack overflow
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。
另一种解释方式:
// Not realistic but ideal for understanding the axis parameter df = pd.DataFrame([[1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 3]], columns=["idx1", "idx2", "idx3", "idx4"], index=["idx1", "idx2", "idx3"] )
---------------------------------------1 | idx1 idx2 idx3 idx4 | idx1 1 1 1 1 | idx2 2 2 2 2 | idx3 3 3 3 3 0 关于df.drop(轴表示位置)
A: I wanna remove idx3. B: Which one? // typing while waiting response: df.drop("idx3", A: The one which is on axis 1 B: OK then it is >> df.drop("idx3", axis=1)
// Result ---------------------------------------1 | idx1 idx2 idx4 | idx1 1 1 1 | idx2 2 2 2 | idx3 3 3 3 0 关于df.apply(轴表示方向)
A: I wanna apply sum. B: Which direction? // typing while waiting response: df.apply(lambda x: x.sum(), A: The one which is on parallel to axis 0 B: OK then it is >> df.apply(lambda x: x.sum(), axis=0)
// Result idx1 6 idx2 6 idx3 6 idx4 6