pandas使用笔记
pandas使用笔记
基础概念
- DataFrame类
# 注:[]表示里面是传入参数
# 属性
DataFrame.index # 取序列号
DataFrame.columns # 取表的字段
DataFrame.info([...]) # 表的统计总结
DataFrame.values # 返回Numpy格式
# Indexing, iteration
DataFrame.head([n]) # 返回前n行数据
DataFrame.loc
DataFrame.iloc
DataFrame.insert([loc, column, value[,...]])
DataFrame.items()
DataFrame.where()
DataFrame.query()
# Function applicatoin, GroupBy & window
DataFrame.apply(func[,axis=0,raw,...]) # apply a function along an axis of the DataFrame. 逐行或者逐列处理
DataFrame.applymap(func[,na_action]) # apply a function to a DataFrame elementwise. 逐个应用
DataFrame.aggregate([func, axis]) # aggregate using one or more operations over the specified axis.
DataFrame.groupby([by, axis, level, ...]) # Group DataFrame using a mapper or by a Series of columns.
- 删除行
df = df.drop([<row>.index])
- 选择
df[df['name'].isin(['Jonh', 'Lucy'])]
- 排序
df.sort_values(by=['data_date'])
- 创建空的Dataframe,逐行添加数据
df = pd.DataFrame(columns=['a', 'b'])
df = df.append(your_data, ignore_index=True) # 要注意忽略索引
- 硬编码和one-hot编码
# 硬编码(通过key-value获取对应的数字)
from sklearn.preprocessing import LabelEncoder
encoder = LabelEncoder().fit(data["feature"])
data["feature"] = encoder.transform(data["feature"])
# one-hot编码
pd.get_dummies(data['color'], prefix='color') ## 其中 prefix 为新的特征名称前缀
-
axis
axis=0表示是行操作, axis=1表示列操作 -
how
- 内连接
inner
:指连接结果仅包含符合连接条件的行,参与连接的两个表都应该符合连接条件。 - 外连接
outer
:连接结果不仅包含符合连接条件的行同时也包含自身不符合条件的行。包括左外连接、右外连接和全外连接。 - 左(外)连接
left
:左边表数据行全部保留,右边表保留符合连接条件的行。 - 右(外)连接
right
:右边表数据行全部保留,左边表保留符合连接条件的行。 - 全外连接:左外连接 union 右外连接,Mysql 中暂不支持。
日期处理
# 取星期几
d=datetime.datetime.now()
d.weekday()
数据比较
数据比较 | 函数 | 使用场景 |
---|---|---|
数据对比 | pd.compare(other, align_axis=1, keep_shape=False, keep_equal=False) |
比较两个DataFrame 或 Series,并总结它们之间的差异 |
数据相同 | DataFrame.equals(other) |
将两个Series或DataFrame相互比较,以查看它们是否具有相同的形状和元素。 相同位置的NaN被认为是相等的。 列标题不必具有相同的类型,但是列中的元素必须具有相同的dtype。 |
数据对齐 | DataFrame.align() |
使得两个数据帧之间的行和/或列的排列相同,而不改变两个数据帧中包含的任何数据 |
每天进步一点点!
©版权声明
文章版权归作者所有,未经允许请勿转载。