[Python基础] 3.Pandas:数据分析库

版权声明:Hello https://blog.csdn.net/Edward_is_1ncredible/article/details/81907641
import pandas as pd
import numpy as np

I.数据结构
1.Series
s = pd.Series([i * 2 for i in range(1,11)])  # 创建一个10位的序列
print(type(s))
dates= pd.date_range("20170301", periods=8)  # 创建一个从20170301起的往后8位的日期
print(dates)
2.DataFrame
df = pd.DataFrame(np.random.randn(8,5), index=dates, columns=list("ABCDE"))  # 创建一个8*5的随机数矩阵,且索引为dates,列名为list对应内容
print(df)

II.基本操作
1.简单操作
print(df.head(3))  # 查看前三个
print(df.tail(3))  # 查看后三个
print(df.index)  # 查看索引
print(df.values)  # 查看除掉索引的纯内容
print(df.T)  # 查看转置
print(df.sort_values(by=["B"],ascending=False))  # 对B列进行降序排列
print(df.sort_index(ascending=False))  # 对索引进行降序排列
print(df.describe())  # 数据概览,大致了解每列的平均数等基本统计量
2.切片操作
print(df["A"])  # 对A这一列进行列切片
print(type(df["A"]))  # 注:列切片的格式为Series,可见DataFrame是由Series构成的
print(df[:3])  # 对前X行进行行切片
print(df.loc["20170301":"20170304"])  # 根据索引选择其中的20170301-20170304这几行
print(df.loc["20170301":"20170304",["B","D"]])  # 选取指定行的指定列
print(df.iloc[1:3,2:4])  # 根据下标切片,上限不在内
print(df.iloc[1,4])  # 指定位置的数值
3.条件筛选
print(df[df.B>0][df.A<0])  # 筛选df中B列>0,A列<0的信息
print(df[df>0])  # 筛选df中>0的信息,不满足条件的NaN
print(df[df["E"].isin([1,2])])  # 类似SQL的IN
4.DataFrame的设置
# 1)新添加一列
s1 = pd.Series(list(range(10,18)),index=pd.date_range("20180301",periods=8))
df["F"] = s1
print(s1)
# 2)修改一格信息
df.iat[1,1] = 100
print(df)
# 3)修改一列信息,修改D列内容为7*df长度的列表
df.loc[:,"D"] = np.array([7] * len(df))
# 4)拷贝,并将df2中正值全改为负值
dfc = df.copy()
dfc[dfc>0] = -dfc
print(dfc)

III.缺失值处理
df1 = df.reindex(index=dates[:4],columns=list("ABCD")+["G"])
df1.loc[dates[0]:dates[1],"G"] = 1
print(df1)
# 1)直接丢弃
print(df1.dropna())
# 2)填充空值为2
print(df1.fillna(value=2))

IV.统计,表的拼接,形状的重塑
1.统计
print(df.mean())  # 求均值等
s = pd.Series([1,2,4,np.nan,5,7,9,10],index=dates)
print(s)
print(s.shift(2))  # 每个填充两个,很难描述,自行尝试
print(s.diff())  # 差分
print(s.value_counts())  #每个值在series中的个数,用作画直方图
print(df.apply(np.cumsum))  # 利用apply引用函数,此处引用了累加函数
print(df.apply(lambda x: x.max()-x.min()))  # 引用自定义匿名函数
2.表的拼接
# 1)拼接前三行和最后一行
piece = [df[:3],df[:-1]]
print(pd.concat(piece))
# 2)两个DF的拼接
left = pd.DataFrame({"key":["x","y"],"value":[1,2]})
right = pd.DataFrame({"key":["x","z"],"value":[3,4]})
print(pd.merge(left,right,on="key",how="left"))
# 注:类似SQL的JOIN,on对应了拼接关键词,how对应了方法(left,right,inner,outer)
# 3)聚合,要设置聚合方式(sum这类的)
df3 = pd.DataFrame({"A":["a","b","c","b"],"B":list(range(4))})
print(df3.groupby("A").sum())
# 4)交叉分析的透视表
import datetime
df4 = pd.DataFrame({"A":["one","one","two","three"]*6,
                    "B":["a","b","c"]*8,
                    "C":["foo","foo","foo","bar","bar","bar"]*4,
                    "D":np.random.randn(24),
                    "E":np.random.randn(24),
                    "F":[datetime.datetime(2017,i,1) for i in range(1,13)]+
                        [datetime.datetime(2017,i,15) for i in range(1,13)]})
print(pd.pivot_table(df4,values="D",index=["A","B"]))  # 对应了数据源,输出值,透视项

V.时间序列,绘图及文件相关
1.时间序列
t_exam = pd.date_range("20170301",periods=10,freq="S")  # freq对应了间隔
print(t_exam)
2.绘图
ts = pd.Series(np.random.randn(1000),index=pd.date_range("20170301",periods=1000))
# one way:
import matplotlib.pyplot as plt
plt.plot(ts)
plt.show()
# another way
from pylab import *
ts.plot()
show()
3.文件操作
df6 = pd.read_csv() # 读取csv
df6.to_csv() # 保存
df7 = pd.read_excel(."sheet1") # 读取excel
df7.to_excel() # 保存

猜你喜欢

转载自blog.csdn.net/Edward_is_1ncredible/article/details/81907641