Pandas系列教程(5)Pandas數據統計函數


Pandas數據統計函數

1、讀取csv數據

import pandas as pd

file_path = "../../datas/files/beijing_tianqi_2018.csv"
df = pd.read_csv(file_path)

# 替換溫度的后綴℃, 並轉為int32(修改列)
df.loc[:, 'bWendu'] = df.loc[:, 'bWendu'].str.replace('', '').astype('int32')
df.loc[:, 'yWendu'] = df.loc[:, 'yWendu'].str.replace('', '').astype('int32')

print(df.head(3))

 

2、匯總類統計

import pandas as pd

file_path = "../../datas/files/beijing_tianqi_2018.csv"
df = pd.read_csv(file_path)

# 替換溫度的后綴℃, 並轉為int32(修改列)
df.loc[:, 'bWendu'] = df.loc[:, 'bWendu'].str.replace('', '').astype('int32')
df.loc[:, 'yWendu'] = df.loc[:, 'yWendu'].str.replace('', '').astype('int32')

# 打印前三行
print('*' * 25, '打印前三行的數據', '*' * 25)
print(df.head(3))

# 提取所有數字列統計結果
print('*' * 25, '提取所有數字列統計結果', '*' * 25)
print(df.describe())

# 查看單個Series的數據
print('*' * 25, '查看單個Series的數據', '*' * 25)
print(df['bWendu'].mean())
# 最高溫
print(df['bWendu'].max())
# 最低溫
print(df['yWendu'].min())

 

3、唯一去重和按值計數

import pandas as pd

file_path = "../../datas/files/beijing_tianqi_2018.csv"
df = pd.read_csv(file_path)

# 替換溫度的后綴℃, 並轉為int32(修改列)
df.loc[:, 'bWendu'] = df.loc[:, 'bWendu'].str.replace('', '').astype('int32')
df.loc[:, 'yWendu'] = df.loc[:, 'yWendu'].str.replace('', '').astype('int32')

# ---------------------- 1 唯一去重性 ------------------------- #
# 一般不用於數值列,而是枚舉,分類列
print('*' * 25, '唯一去重性', '*' * 25)
print(df['fengxiang'].unique())
print(df['tianqi'].unique())
print(df['fengli'].unique())

# ---------------------- 2 按值計數 ------------------------- #
print('*' * 25, '按值計數', '*' * 25)
print(df['fengxiang'].value_counts())
print(df['tianqi'].value_counts())
print(df['fengli'].value_counts())

 

4、相關系數和協方差

用途(超級厲害):

  1. 兩支股票,是不是同漲同跌?程度多大?正相關還是負相關?

  2. 產品銷量的波動,跟那些因素正相關,負相關,程度有多大?

來自知乎,對於兩個變量X,Y

  1. 協方差:衡量同向反向程度,如果協方差為正,說明X,Y同向變化。協方差越大說明同向程度越高;如果協方差為負,說明X,Y反向運動,協方差越小說明反向程度越高。

  2. 相關系數:衡量相似程度,當他們的相關系數為1時,說明兩個變量變化是的正向相似度最大,當相關系數為-1時,說明兩個變量的反向相似度最大

import pandas as pd

file_path = "../../datas/files/beijing_tianqi_2018.csv"
df = pd.read_csv(file_path)

# 替換溫度的后綴℃, 並轉為int32(修改列)
df.loc[:, 'bWendu'] = df.loc[:, 'bWendu'].str.replace('', '').astype('int32')
df.loc[:, 'yWendu'] = df.loc[:, 'yWendu'].str.replace('', '').astype('int32')

# 協方差矩陣
print('*' * 25, '協方差矩陣', '*' * 25)
print(df.cov())

# 相關系數矩陣
print('*' * 25, '相關系數矩陣', '*' * 25)
print(df.corr())

# 單獨查看空氣質量和最高溫度的相關系數
print('*' * 25, '單獨查看空氣質量和最高溫度的相關系數', '*' * 25)
print(df['aqi'].corr(df['bWendu']))
print(df['aqi'].corr(df['yWendu']))

# 空氣質量和溫度差的相關系數
print('*' * 25, '空氣質量和溫度差的相關系數', '*' * 25)
print(df['aqi'].corr(df['yWendu'] - df['bWendu']))

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM