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_pathparameter (so you can reuse the function for different CSV files) - Uses
pd.read_csv()to load the data, with thenamesargument 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

