Pandas是Python中用于数据分析的一个强大的库,它提供了许多功能丰富的函数。本文介绍其中高频使用的30个函数。

read_csv(): 从CSV文件中读取数据并创建DataFrame对象。
import pandas as pd
df = pd.read_csv('data.csv')
read_excel(): 从Excel文件中读取数据并创建DataFrame对象。
df = pd.read_excel('data.xlsx')
to_excel(): 输出数据并保存在新的excel文件中。
df.to_excel('data_output.xlsx')
head(): 返回前n行数据(默认为5)。
print(df.head(5))
tail(): 返回最后n行数据(默认为5)。
print(df.tail(5))
shape: 返回DataFrame的形状(行数和列数)。
rows, cols = df.shape
print(f"Rows: {rows}, Columns: {cols}")
columns: 返回DataFrame的列名列表。
column_names = df.columns
print(column_names)
index: 返回DataFrame的索引列表。
index_list = df.index
print(index_list)
describe(): 生成描述性统计信息,包括计数、平均值、标准差等。
statistics = df.describe()
print(statistics)
info(): 返回DataFrame的信息摘要,包括索引、列、非空值数量和内存信息。
print(df.info())
dtypes: 返回每列的数据类型。
data_types = df.dtypes
print(data_types)
drop(): 删除指定行或列。
df = df.drop('column_name', axis=1)
sort_values(): 根据指定列的值对DataFrame进行排序。
df_sorted = df.sort_values('column_name')
loc[]: 通过标签选择数据。
df=pd.DataFrame({'Column1': [1,0,0,0,0,0,2,2],
'Column2': [1,1,0,0,0,0,2,2],
'Column3': [0,0,0,1,0,0,2,2],
'Column4': [1,0,0,1,0,0,2,2]})
df.loc[:,'Column2']
iloc[]: 通过整数位置选择数据。
cell_data = df.iloc[1, 2]
at[]: 选择单个元素。
element_value = df.at[1, 'Column4']
iat[]: 选择单个元素。
element_value = df.iat[1, 2]
isnull(): 检查缺失值。
missing_values = df.isnull()
notnull(): 检查非缺失值。
non_missing_values = df.notnull()
fillna(): 填充缺失值。
df_filled = df.fillna(0)
replace(): 替换值。
df_replaced = df.replace(old_value, new_value)
rename(): 重命名列名。
df_renamed = df.rename(columns={'old_name': 'new_name'})
set_index(): 设置索引列。
df_indexed = df.set_index('column_name')
reset_index(): 重置索引。
df_reset = df.reset_index()
groupby(): 根据指定列对数据进行分组。
grouped = df.groupby('column_name')
agg(): 对分组后的数据应用聚合函数。
aggregated = grouped.agg({'column_name': ['sum', 'mean']})
unique(): 查找该列唯一值。
df=pd.DataFrame({'Column1': [1,0,0,0,0,0,2,2],
'Column2': [1,1,0,0,0,0,2,2],
'Column3': [0,0,0,1,0,0,2,2],
'Column4': [1,0,0,1,0,0,2,2]})
list(df['Column1'].unique())#唯一值是0,1,2
concat(): 连接两个或多个DataFrame。
df_concatenated = pd.concat([df1, df2])
merge(): 合并两个DataFrame,根据一个或多个键进行连接。
merged_df = pd.merge(df1, df2, on='key')
apply(): 应用函数至指定行或列。
df['new_column'] = df['column_name'].apply(lambda x: x * 2) # 对列应用函数
以上这些函数覆盖了从数据加载、预处理、转换到分析的各个阶段。Pandas的强大之处在于其函数的灵活性和易用性,使得数据分析工作变得简单高效。