To get the number of rows (or length) of a Pandas DataFrame df, you can use the len() function or the shape attribute. Here's how to do it with examples:
Using the len() function:
python
import pandas as pd
# Sample DataFrame
data = {'Column1': [1, 2, 3, 4, 5],
        'Column2': ['A', 'B', 'C', 'D', 'E']}
df = pd.DataFrame(data)
# Get the number of rows using len()
num_rows = len(df)
print("Number of rows using len():", num_rows)
In this example, len(df) returns the number of rows in the DataFrame df.
Using the shape attribute:
python
import pandas as pd
# Sample DataFrame
data = {'Column1': [1, 2, 3, 4, 5],
        'Column2': ['A', 'B', 'C', 'D', 'E']}
df = pd.DataFrame(data)
# Get the number of rows using shape
num_rows = df.shape[0]
print("Number of rows using shape:", num_rows)
In this example, df.shape[0] returns the number of rows in the DataFrame df. The shape attribute returns a tuple with two elements: the number of rows and the number of columns, so accessing the first element (shape[0]) gives you the number of rows.
Both methods will give you the same result, which is the number of rows in the DataFrame.
Comments
Post a Comment