pandas tutorial

Series

特点:

  • 可以容纳各种数据类型

  • 创建后大小不变

  • 可以包含缺失数据NaN

创建Series

使用pd.Series(data=,index=,dtype=,name=,copy=,fastpath=)创建Series

index参数用于指定索引(一般是一个数组)

1
2
3
a=[1,2,3]
myavr=pd.Series(a,index=["x","y","z"])
print(myvar["y"])

output:2

使用字典可以直接指定索引:

1
2
3
4
5
a={"x":1,"y":2,"z":3}

myvar=pd.Series(a)

print(a["x"])

output:1

如果只需要字典一部分值则直接指定索引,对应索引的值会被保留

常用方法

  • index:获取索引
  • value:获取数据
  • head(n):获取series的前n行
  • tail(n):获取series的后n行
  • dtype:数据类型
  • shape:行数
  • describe():返回Series的统计描述的series
  • isnull():返回布尔Series,表示是否每一个元素都是NaN
  • notnull():表示每个元素是否不是NaN
  • unique():去重
  • value_count():统计值出现的次数
  • map(func)\apply(func):将指定函数应用于每一个元素
  • astype(dtype):将series转换为指定的数据类型
  • sort_value():将series根据value排序
  • sort_index():将series按照index排序
  • dropna():将缺失值NaN删除
  • fillna(value):填充缺失值
  • replace(to_replace,value):替换series中指定值
  • cumsum():累计求和
  • cumprod():累计求积
  • shift(period):位移
  • rank():返回元素排名
  • corr(other):计算皮尔逊相关系数
  • cov(other):计算协方差
  • to_list():将series转换为列表
  • to_frame():将series转换为dataframe
  • iloc():通过位置索引
  • loc():按照标签索引

DataFrame

DataFrame类似于二维表格

既有行索引也有列索引

DataFrame构造方法

1
pandas.DataFrame(data=,index=,columns=,dtype=,copy=)

index:行索引

columns:列索引

数据清洗

常见步骤:

  1. 缺失值处理
  2. 重复数据处理
  3. 异常值处理
  4. 数据格式转换
  5. 标准化与归一化
  6. 归一化
  7. 类别数据编码
  8. 文本处理
  9. 数据抽样
  10. 特征工程

清洗空值

1
dataframe.dropna(axis=,how=,thresh=,subset=,inplace=)

axis:逢空去除0:行 1:列

how:’any’只要有就去除还是’all’全都是空值才去除

thresh=多少空值可以保留

subset:设置想要检查的列

inplace:是否修改源数据

在read_csv函数中可以添加na_values=[]的参数添加将什么值认定为空值

1
dataframe.fillna(value=,method=,axis=,inplace=,limit=)

limit:限制填充几个空值

method:’ffill’用前一个有效值填充‘bdfill’用后一个有效值填充

常用高级填充:

mean():均值

median():中位数

mode():众数

清洗错误格式数据

1
2
3
for x in df.index:
if df.loc[x, "age"] > 120:
df.loc[x, "age"] = 120
1
2
3
for x in df.index:
if df.loc[x, "age"] > 120:
df.drop(x, inplace = True)

清洗重复数据

1
DataFrame.duplicated(subset=None, keep='first')

参数

参数 说明
subset 指定判断重复的列(默认所有列)
keep 保留策略: - 'first'(默认):标记重复行,但第一个出现的不标记 - 'last':标记重复行,但最后一个出现的不标记 - False所有重复行均标记为True
1
DataFrame.drop_duplicates(subset=None, keep='first', inplace=False, ignore_index=False)

参数

参数 说明
subset 指定判断重复的列(默认所有列)
keep 保留策略: - 'first'(默认):保留第一个出现的行 - 'last':保留最后一个出现的行 - False删除所有重复行
inplace 是否原地修改数据(默认 False,返回新对象)
ignore_index 是否重置索引(默认 False,保留原索引)

性能优化

  • 大数据集:使用 subset 指定关键列减少计算量。
  • 内存优化inplace=True 可减少内存占用(但慎用,会直接修改原数据)。
Author

SAI_MUD

Posted on

2025-04-24

Updated on

2025-04-25

Licensed under