Top 10 Most Common Pandas Functions with Code Examples
This article introduces the ten most commonly used Pandas functions—read_csv, head, tail, info, describe, dropna, fillna, groupby, merge, and to_csv—explaining their purposes and providing clear Python code examples for each in practical data analysis tasks.
Pandas is a powerful Python library for data analysis, offering numerous functions to efficiently process data. Below are the ten most frequently used Pandas functions, each with a brief description and example code.
1. read_csv() reads data from a CSV file into a DataFrame.
import pandas as pd
# 从CSV文件读取数据
df = pd.read_csv('data.csv')
print("从CSV文件读取的数据:")
print(df)2. head() displays the first n rows of a DataFrame (default 5).
# 显示前5行
print("显示前5行:")
print(df.head())3. tail() displays the last n rows of a DataFrame (default 5).
# 显示后5行
print("显示后5行:")
print(df.tail())4. info() provides basic information about a DataFrame, including column names, data types, and non‑null counts.
# 获取DataFrame的基本信息
print("获取DataFrame的基本信息:")
print(df.info())5. describe() generates descriptive statistics such as count, mean, std, min, and max.
# 生成描述性统计信息
print("生成描述性统计信息:")
print(df.describe())6. dropna() removes rows or columns containing missing values.
# 删除包含缺失值的行
df_clean = df.dropna()
print("删除包含缺失值的行后的DataFrame:")
print(df_clean)7. fillna() fills missing values with a specified value.
# 填充缺失值
df_filled = df.fillna(0)
print("填充缺失值后的DataFrame:")
print(df_filled)8. groupby() groups data by a specified key and performs aggregation.
# 按某一列分组并计算均值
grouped_df = df.groupby('column_name').mean()
print("按某一列分组并计算均值后的DataFrame:")
print(grouped_df)9. merge() merges two DataFrames on a common column.
# 创建另一个DataFrame
df2 = pd.DataFrame({
'column_name': ['A', 'B', 'C'],
'value': [1, 2, 3]
})
# 合并两个DataFrame
merged_df = pd.merge(df, df2, on='column_name')
print("合并两个DataFrame后的结果:")
print(merged_df)10. to_csv() exports a DataFrame to a CSV file.
# 将DataFrame导出为CSV文件
df.to_csv('output.csv', index=False)
print("已导出为CSV文件")These ten functions cover data loading, preprocessing, analysis, and export, making them essential tools for effective data analysis with Pandas.
Test Development Learning Exchange
Test Development Learning Exchange
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.