数据分析(排序,数据特征、平均数、方差等,累计统计,相关分析)

# hanbb
# come on!!!
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

df = pd.DataFrame(np.arange(12).reshape(3,4),index=['b','a','c'],columns=['2nd','1st','4or','3rd'])
print(df)
# 排序

# 根据行列排序
print(df.sort_index(axis=0,ascending=True))  # 默认是列索引,升序
print(df.sort_index(axis=1))                  # 行索引

# 根据某行或者某列的值排序
print(df.sort_values('1st'))                        # 默认是列,升序列
print(df.sort_values('a',axis=1,ascending=False))  # 改为行,降序

# 求和
print(df.sum())
print(df.sum(axis=1))
# 累计求和
print(df.cumsum())
print(df.cumsum(axis=1))
# 数量
print(df.count())
print(df.count(axis=1))

# 数据操作
print(df.mean())         # 平均数
print(df.median())       # 中位数
print(df.max())          # 最大值
print(df.min())          # 最小值
print(df.var())          # 方差
print(df.std())          # 标准差

# 数据特征
a = df.describe()        # 求出所有的数据特征
print(a.ix['max'])       # ix 怎么用???

# 累计操作
print(df.cumsum())     # 累计求和
print(df.cumprod())    # 累计乘积
print(df.cummax())     # 累计最大值
print(df.cummin())     # 累计最小值

# 累计统计,滚动分布
print(df.rolling(2).sum())   # 相邻2个元素的和
print(df.rolling(2).mean())  # 相邻2个元素的平均值
print(df.rolling(2).var())   # 相邻2个元素的方差
print(df.rolling(2).std())   # 相邻2个元素的标准
print(df.rolling(2).min())   # 相邻2个元素的最小值
print(df.rolling(2).max())   # 相邻2个元素的最大值

# 相关分析

df1 = pd.Series(np.arange(1,5),index=['a','b','c','d'])  # 1.66666666667
df2 = pd.Series(np.arange(5,9),index=['a','b','c','d'])  # 1.0

# plt.plot(df1.values)
# plt.plot(df2.values)
# plt.show()

print(df1.cov(df2))  # 协方差,正相关>0,负相关<0,无关=0
print(df1.corr(df2)) # pearson 相关   0.8到1极强相关,0.6-0.8强相关;0.4-0.6中等相关;0.2-0.4弱相关,0-0.2极弱相关或无关

df3 = pd.Series(np.random.randint(1,5),index=['a','b','c','d'])  # 0.0
df4 = pd.Series(np.random.randint(5,9),index=['a','b','c','d'])  # nan
print(df3.cov(df4))
print(df3.corr(df4))
print(df3)
print(df4)
plt.scatter(df3.values,df4.values)
plt.show()
原文地址:https://www.cnblogs.com/hanbb/p/7861766.html