如何获取 Pandas DataFrame 的行数? [英] How do I get the row count of a Pandas DataFrame?

查看:67
本文介绍了如何获取 Pandas DataFrame 的行数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 Pandas 获取数据帧 df 的行数,这是我的代码.

方法一:

total_rows = df.count打印 total_rows + 1

方法 2:

total_rows = df['First_column_label'].count打印 total_rows + 1

两个代码片段都给我这个错误:

<块引用>

TypeError: 不支持 + 的操作数类型:'instancemethod' 和 'int'

我做错了什么?

解决方案

对于数据帧 df,可以使用以下任何一种:

  • len(df.index)
  • df.shape[0]
  • df[df.columns[0]].count() (==


    重现情节的代码:

    将 numpy 导入为 np将熊猫导入为 pd导入性能图perfplot.save("out.png",setup=lambda n: pd.DataFrame(np.arange(n * 3).reshape(n, 3)),n_range=[2**k for k in range(25)],内核=[lambda df: len(df.index),拉姆达 df: df.shape[0],lambda df: df[df.columns[0]].count(),],标签=[len(df.index)", df.shape[0]", df[df.columns[0]].count()"],xlabel=行数",)

    I'm trying to get the number of rows of dataframe df with Pandas, and here is my code.

    Method 1:

    total_rows = df.count
    print total_rows + 1
    

    Method 2:

    total_rows = df['First_column_label'].count
    print total_rows + 1
    

    Both the code snippets give me this error:

    TypeError: unsupported operand type(s) for +: 'instancemethod' and 'int'

    What am I doing wrong?

    解决方案

    For a dataframe df, one can use any of the following:


    Code to reproduce the plot:

    import numpy as np
    import pandas as pd
    import perfplot
    
    perfplot.save(
        "out.png",
        setup=lambda n: pd.DataFrame(np.arange(n * 3).reshape(n, 3)),
        n_range=[2**k for k in range(25)],
        kernels=[
            lambda df: len(df.index),
            lambda df: df.shape[0],
            lambda df: df[df.columns[0]].count(),
        ],
        labels=["len(df.index)", "df.shape[0]", "df[df.columns[0]].count()"],
        xlabel="Number of rows",
    )
    

    这篇关于如何获取 Pandas DataFrame 的行数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆