简介
pandas is a fast, powerful, flexible and easy to use open source data analysis and manipulation tool,
built on top of the Python programming language.
numpy 虽然能够帮助我们处理数值,但是pandas除了处理数值之外(基于numpy),还能够帮助我们处理其他类型的数据(字符串、时间序列等等)。
- DataFrame 二维,Series容器
Series
Series 一维,带标签数组(索引),本质上为对象的 key 和 对象的值 values 组成的序列,同时 index 有序
import pandas as pd
import numpy as np
import string
# 创建 ascii 序列
s = pd.Series(np.arange(10), index=list(string.ascii_uppercase[:10]))
# 转换 value 的类型
s = astype(float)
# 对象转为序列
# 对象 key value 都会保留,且有序
s = pd.Series({"name": "xiaoming", "age": 18, "tel": 110})
# 取值可以通过 key 和 index
out = s[key]
out = s[0]
out = s[["name", "age"]]
# 获取所有下标
out = s.index
# 下标类型
out = type(s.index)
# 下标长度
out = len(s.index)
# 下标切片
out = list(s.index)[:2]
# value 类型
out = type(s.values)
更多方法
ndarray 的很多方法都可以直接套用,如 argmax, clip
- 注意 where 方法和 ndarray 不同
文档:https://pandas.pydata.org/docs/reference/api/pandas.Series.html
读取外部文件
# 读取磁盘
pd.read_csv(path)
# 读取 sql connection
pd.read_sql(connection)
# max min 的值
s.max()
s.min()
# max min 的坐标
s.argmax()
s.argmin()
# 中位数
s.median()
DataFrame
DataFrame 是二维,Series 容器
-
DataFrame 对象既有行索引,又有列索引
- 行索引,表明不同行,横向索引,叫index,0轴,axis=0
- 列索引,表名不同列,纵向索引,叫columns,1轴,axis=1
-
和 Series 关系:
- df[column] 就是 Series
import pandas as pd
import numpy as np
f = pd.DataFrame(np.arange(12).reshape(3, 4),
# 行索引
index=list("abc"),
# 列索引
columns=list("WXYZ"))
print(f)
输出:
W X Y Z
a 0 1 2 3
b 4 5 6 7
c 8 9 10 11
字典形式:
df = pd.DataFrame({"name": ["xiaoming", "xiaogang"],
"age": [20, 31],
"tel": [10010, 10011]})
print(f)
print(df)
输出:
name age tel
0 xiaoming 20 10010
1 xiaogang 31 10011
json 数组形式, 自动填充 nan:
df = pd.DataFrame([{
"name": "xiaoming",
"age": 20,
"tel": 10010
}, {
"name": "xiaohong",
"age": 33,
"tel": 10012
}])
print(df)
输出:
name age tel
0 xiaoming 20 10010
1 xiaohong 33 10012
其他方法:
# 头几行
out = df.head(1)
# 后几行
out = df.tail(2))
# 概览,如数组容量等
out = df.info())
# 描述
out = df.describe())
# 按照列排序
out = df.sort_values(by="col", asceding=False)
取值
取行列:
# 取行
out = df[:20]
# 取列
# 就是 key 为 index 的 Series
out = df["Row_Labels"]
# 组合某些行的某列
out = df[:20]["Row_Labels"]
df.loc
通过标签取值
# 具体 index 的 column
df.loc[[index, column]]
# 整行
df.loc[[index]]
df.loc[[index, :]]
# 整列
df.loc[[:, column]]
# 某些行
df.loc[[index0, index1]]
df.loc[[index0, index1], :]
# 某些列
df.loc[:, [column0, column1]]
# 某些行某些列
df.loc[[index0, index1], [column0, column1]]
# index 支持区间
df.loc[index0:index1, [column0, column1]]
df.iloc
通过位置(坐标)取值
# 通过坐标取某行值
df.iloc[1]
df.iloc[1, :]
# 通过坐标取列值
df.iloc[: 1]
# 取某行某列
df.iloc[[0, 2], [2, 1]]
df.iloc[:2, 2:]
# 支持直接赋值 nan 不需要 cast to float
df.iloc[:2, 2:] = nan
布尔索引
# 选择 value 800 到 1000 的行
out = df[(df[column] > 800) & (df[column] < 1000)]
字符串方法
# 选择 value 长度大于 4 的行
df[df[column].str.len() > 4]
# 某列的所有字符串 split 后分别转 list
df[column].str.split(splitter).tolist()
缺失数据处理
# 批量判断是否 NaN
pandas.isnull(df)
pandas.notnull(df)
# 例子:选择某列不为 NaN 的 df (条件为布尔索引)
df[pd.notnull(pd[column])]
# 删除某个坐标(0=index or 1=column) NaN
df.dropna(axis=0,
# any 存在一个 NaN; all 全部都是 NaN
how="all"
# 原地修改
inplace=True)
# 填充均值
df.fillna(df.mean())
# 填充某列均值
df[column].fillna(df[column].mean())
# 0 转为 NaN
df[df==0]=numpy.nan
注意 NaN 默认不参与运算,0参与,因此后端返回数据最好可以不填,不要用 0 或者空串兜底,业务来做兜底
Pandas 是一款基于 Python 的开源数据分析与处理工具,支持快速、灵活且高效的数据操作。本文介绍了 Pandas 中 Series 和 DataFrame 的使用方法,包括创建、索引、读取文件、基本统计分析及数据筛选等内容。
1278

被折叠的 条评论
为什么被折叠?



