Pandas基础知识随笔

python学习网 2020-07-28 21:58:01
#!/usr/bin/python3
# -*- coding: UTF-8 -*-
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt


def main():
# 创建一个列表Series,pandas会创建整形指标

s = pd.Series([1, 2, 3, np.nan, 6, 8])
print(s)

# 通過传递数据字相同的数组,时间索引,列标签创建DataFrame

dates = pd.date_range('20130101', periods=6)
print(dates)

# 上下文联系

df = pd.DataFrame(np.random.randn(6, 4), index=dates, columns=list('ABCD'))
print(df)

# 字典模式
df2 = pd.DataFrame({
'A': 1.,
'B': pd.Timestamp('20130102'),
'C': pd.Series(1, index=list(range(4)), dtype='float32'),
'D': np.array([3] * 4, dtype='int32'),
'E': pd.Categorical(["test", "train", "test", "train"]),
'F': 'foo'})
print(df2)

# 查看格列dtype
print(df2.dtypes)

###第二部分查看所有基本功能
# 头
print(df.head())

# 尾
print(df.tail(3))

# 查看索引,列和数组数据
print(df.index)

# 查看列
print(df.columns)

# 查看值
print(df.values)

# 查看数据快速统计
print(df.describe())

# 对数据列转换
print(df.T)

# 按照行排序
print(df.sort_index(axis=1, ascending=False))

# 按照值排序
print(df.sort_values(by='B'))

# 选择数据 标准Python/Numpy 表达式直观可用

# 获取 选择一列返回Series
print(df['A'])

# 通过[]选择 进行切片
print(df[0:3])

# 标签选择,通过标签获取交叉区域
print(df.loc[dates[0]])

# 通过标签获取更多的数据
print(df.loc[:, ['A', 'B']])

# 标签切片
print(df.loc['20130102':'20130104', ['A', 'B']])

# 返回对象缩减维度
df.loc['20130102', ['A', 'B']]

# 获取单个值
print(df.loc[dates[0], 'A'])

# 快速访问单个标量
print(df.at[dates[0], 'A'])

# loc 和 iloc 的区别 loc按标签搜索,iloc按索搜索
print(df.iloc[3])

# 通过数值切片 左开右闭
print(df.iloc[3:5, 0:2])

# 通过指定表位置
print(df.iloc[[1, 2, 4], [0, 2]])

# 对行切片
print(df.iloc[1:3, :])

# 对列切片
print(df.iloc[:, 1:3])

# 获取特定值
print(df.iloc[1, 1])

# 通过某;列选择数据
print(df[df.A > 0])

# 通过where选择数据
print(df[df > 0])

# 通过isin()过滤数据
df2 = df.copy()
df2['E'] = ['one', 'one', 'two', 'three', 'four', 'three']
print(df2)

print(df2[df2['E'].isin(['two', 'four'])])

# 通过标签更新值
df.at[dates[0], 'A'] = 0

# 通过位置更新值
df.iat[0, 1] = 0

# 通过数组更新值
df.loc[:, 'D'] = np.array([5] * len(df))

print(df)

# 通过where更新值
df2 = df.copy()
df2[df2 > 0] = -df2
print(df2)

# 缺失数据处理reindex()可以修改/增加/删除索引,会返回一个数据的副本:
df1 = df.reindex(index=dates[0:4], columns=list(df.columns) + ['E'])
df1.loc[dates[0]:dates[1], 'E'] = 1
print(df1)

# d丢掉缺失行
print(df1.dropna(how='any'))

# 对缺失行 赋值
print(df1.fillna(value=5))

# 对缺失的布尔值赋值
print(pd.isnull(df1))

# 平均值
print(df.mean())

# 按照行求均值
print(df.mean(axis=1))

# 操作不同维护需要对齐,pandas 会沿着指定维度执行
s = pd.Series([1, 2, 5, np.nan, 6, 8], index=dates).shift(2)
print(s)
print(df.sub(s, axis='index'))

"""
注:
这里对齐维度指的对齐时间index
shift(2)指沿着时间轴将数据顺移两位
sub指减法,与NaN进行操作,结果也是NaN

"""
# 应用
# 对数据应用function 注: - cumsum 累加

print(df.apply(np.cumsum))
print(df.apply(lambda x: x.max() - x.min()))

# 直方图
s = pd.Series(np.random.randint(0, 7, size=10))
print(s)

# j计数
print(s.value_counts())

# 支持字符串
s = pd.Series(['A', 'B', 'C', 'Aaba', 'bACA', np.nan, 'CABA', 'dog', 'cat'])
print(s)

# 连接合并
df = pd.DataFrame(np.random.randn(10, 4))
print(df)
pieces = [df[:3], df[3:7], df[7:]]
print(pd.concat(pieces))

# join操作
left = pd.DataFrame({'key': ['foo', 'foo'], 'lval': [1, 2]})
right = pd.DataFrame({'key': ['foo', 'foo'], 'rval': [4, 5]})
print(left)
print(right)
print(pd.merge(left, right, on='key'))

# 追加
df = pd.DataFrame(np.random.randn(8, 4), columns=['A', 'B', 'C', 'D'])
print(df)

s = df.iloc[3]
print(s)
print(df.append(s, ignore_index=True))

# group by 操作
df = pd.DataFrame({'A': ['foo', 'bar', 'foo', 'bar', 'foo', 'bar', 'foo', 'foo'],
'B': ['one', 'one', 'two', 'three', 'two', 'two', 'one', 'three'],
'C': np.random.randn(8),
'D': np.random.randn(8)})

print(df)

# 分组求和
print(df.groupby(['A']).sum())

# 多列求和
print(df.groupby(['A', 'B']).sum())

#绘图
ts=pd.Series(np.random.randn(1000),index=pd.date_range('1/1/2000',periods=1000))
ts=ts.cumsum()
print(ts.plot())
plt.close('all')


if __name__ == '__main__':
main()
阅读(2333) 评论(0)