You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python3中如何用Pandas获取CSV数据集维度、打印行及函数实现

Hey there! Let's walk through how to use Pandas in Python 3 to work with your CSV dataset, including fixing your func1 for loading data, printing the dataset's dimensions, and showing sample rows.

1. Fix and Complete the func1 Dataset Loading Function

Your original code had a few small issues (like overwriting the input parameter), so here's the corrected version that properly loads a CSV with your specified column names:

import pandas as pd

def func1(file_path):
    # Define your custom column names
    names_of_columns = ["The sepal-length", "The sepal-width", 
                        "The petal-length", "The petal-width", "class"]
    # Load the CSV file with the custom column headers
    df = pd.read_csv(file_path, names=names_of_columns)
    return df

# Example usage: Replace with your actual CSV file path
dataset = func1("your_dataset.csv")

Quick breakdown:

  • Takes a file_path parameter (so you can reuse the function for different CSV files)
  • Uses pd.read_csv() to load the data, with the names argument setting your custom column labels
  • Returns the loaded DataFrame for further operations

2. Print the Dataset's Dimensions

Once your DataFrame is loaded, use the shape attribute to get the number of rows and columns:

# Get and print full dimensions
rows, columns = dataset.shape
print(f"Dataset has {rows} rows and {columns} columns")

# Or print the shape tuple directly
print(f"Dataset shape: {dataset.shape}")

The shape attribute returns a tuple where the first value is row count, and the second is column count. If you just need the number of dimensions (e.g., 2 for tabular data), use dataset.ndim.

3. Print Partial Rows of the Dataset

There are several flexible ways to show sample rows from your DataFrame:

Show the first N rows (default is 5)

print("First 5 rows:")
print(dataset.head())

# To show first 10 rows instead:
# print(dataset.head(10))

Show the last N rows (default is 5)

print("\nLast 5 rows:")
print(dataset.tail())

Show random sample rows

print("\nRandom 3 sample rows:")
print(dataset.sample(n=3))

Show specific rows using slicing

# Show rows 10 to 19 (inclusive)
print("\nRows 10-19:")
print(dataset[10:20])

内容的提问来源于stack exchange,提问作者jacky chen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 09:27:27