pandas用法總結

轉載  https://blog.csdn.net/yiyele/article/details/80605909
在後面加了自己比較常用的一些方法代碼

一、生成數據表
1、首先導入pandas庫,一般都會用到numpy庫,所以我們先導入備用:
import numpy as np
import pandas as pd

2、導入CSV或者xlsx文件:
df = pd.DataFrame(pd.read_csv(‘name.csv’,header=1))
df = pd.DataFrame(pd.read_excel(‘name.xlsx’))

3、用pandas創建數據表:

df = pd.DataFrame({"id":[1001,1002,1003,1004,1005,1006], 
     "date":pd.date_range('20130102', periods=6),
     "city":['Beijing ', 'SH', ' guangzhou ', 'Shenzhen', 'shanghai', 'BEIJING '],
     "age":[23,44,54,32,34,32],
     "category":['100-A','100-B','110-A','110-C','210-A','130-F'],
     "price":[1200,np.nan,2133,5433,np.nan,4432]},
     columns =['id','date','city','category','age','price'])

二、數據表信息查看
1、維度查看:
df.shape

2、數據表基本信息(維度、列名稱、數據格式、所佔空間等):
df.info()

3、每一列數據的格式:
df.dtypes

4、某一列格式:
df[‘B’].dtype

5、空值:
df.isnull()

6、查看某一列空值:
df.isnull()

7、查看某一列的唯一值:
df[‘B’].unique()

8、查看數據表的值:
df.values

9、查看列名稱:
df.columns

10、查看前10行數據、後10行數據:
df.head() #默認前10行數據
df.tail() #默認後10 行數據

三、數據表清洗
1、用數字0填充空值:
df.fillna(value=0)

2、使用列prince的均值對NA進行填充:
df[‘prince’].fillna(df[‘prince’].mean())

3、清楚city字段的字符空格:
df[‘city’]=df[‘city’].map(str.strip)

4、大小寫轉換:
df[‘city’]=df[‘city’].str.lower()

5、更改數據格式:
df[‘price’].astype(‘int’)

6、更改列名稱:
df.rename(columns={‘category’: ‘category-size’})

7、刪除後出現的重複值:
df[‘city’].drop_duplicates()

8、刪除先出現的重複值:
df[‘city’].drop_duplicates(keep=’last’)

9、數據替換:
df[‘city’].replace(‘sh’, ‘shanghai’)

四、數據預處理

df1=pd.DataFrame({"id":[1001,1002,1003,1004,1005,1006,1007,1008], 
"gender":['male','female','male','female','male','female','male','female'],
"pay":['Y','N','Y','Y','N','Y','N','Y',],
"m-point":[10,12,20,40,40,40,30,20]})

1、數據表合併
1.1 merge

df_inner=pd.merge(df,df1,how='inner')      # 匹配合並,交集
df_left=pd.merge(df,df1,how='left')        # 左爲主
df_right=pd.merge(df,df1,how='right')      # 右爲主
df_outer=pd.merge(df,df1,how='outer')      # 並集

1.2 append
result = df1.append(df2)
在這裏插入圖片描述

1.3 join
result = left.join(right, on=‘key’)
在這裏插入圖片描述

1.4 concat

pd.concat(objs, axis=0, join='outer', join_axes=None, ignore_index=False,
          keys=None, levels=None, names=None, verify_integrity=False,
          copy=True)

objs︰ 一個序列或系列、 綜合或面板對象的映射。如果字典中傳遞,將作爲鍵參數,使用排序的鍵,除非它傳遞,在這種情況下的值將會選擇 (見下文)。任何沒有任何反對將默默地被丟棄,除非他們都沒有在這種情況下將引發 ValueError。
axis: {0,1,…},默認值爲 0。要連接沿軸。
join: {‘內部’、 ‘外’},默認 ‘外’。如何處理其他 axis(es) 上的索引。聯盟內、 外的交叉口。
ignore_index︰ 布爾值、 默認 False。如果爲 True,則不要串聯軸上使用的索引值。由此產生的軸將標記 0,…,n-1。這是有用的如果你串聯串聯軸沒有有意義的索引信息的對象。請注意在聯接中仍然受到尊重的其他軸上的索引值。
join_axes︰ 索引對象的列表。具體的指標,用於其他 n-1 軸而不是執行內部/外部設置邏輯。
keys︰ 序列,默認爲無。構建分層索引使用通過的鍵作爲最外面的級別。如果多個級別獲得通過,應包含元組。
levels︰ 列表的序列,默認爲無。具體水平 (唯一值) 用於構建多重。否則,他們將推斷鑰匙。
names︰ 列表中,默認爲無。由此產生的分層索引中的級的名稱。
verify_integrity︰ 布爾值、 默認 False。檢查是否新的串聯的軸包含重複項。這可以是相對於實際數據串聯非常昂貴。
副本︰ 布爾值、 默認 True。如果爲 False,請不要,不必要地複製數據。

例子:1.frames = [df1, df2, df3]
2.result = pd.concat(frames)
在這裏插入圖片描述

2、設置索引列
df_inner.set_index(‘id’)

3、按照特定列的值排序:
df_inner.sort_values(by=[‘age’])

4、按照索引列排序:
df_inner.sort_index()

5、如果prince列的值>3000,group列顯示high,否則顯示low:
df_inner[‘group’] = np.where(df_inner[‘price’] > 3000,’high’,’low’)

6、對複合多個條件的數據進行分組標記
df_inner.loc[(df_inner[‘city’] == ‘beijing’) & (df_inner[‘price’] >= 4000), ‘sign’]=1

7、對category字段的值依次進行分列,並創建數據表,索引值爲df_inner的索引列,列名稱爲category和size
pd.DataFrame((x.split(‘-‘) for x in df_inner[‘category’]),index=df_inner.index,columns=[‘category’,’size’]))

8、將完成分裂後的數據表和原df_inner數據表進行匹配
df_inner=pd.merge(df_inner,split,right_index=True, left_index=True)

五、數據提取
主要用到的三個函數:loc,iloc和ix,loc函數按標籤值進行提取,iloc按位置進行提取,ix可以同時按標籤和位置進行提取。

1、按索引提取單行的數值
df_inner.loc[3]

2、按索引提取區域行數值
df_inner.iloc[0:5]

3、重設索引
df_inner.reset_index()

4、設置日期爲索引
df_inner=df_inner.set_index(‘date’)

5、提取4日之前的所有數據
df_inner[:’2013-01-04’]

6、使用iloc按位置區域提取數據
df_inner.iloc[:3,:2] #冒號前後的數字不再是索引的標籤名稱,而是數據所在的位置,從0開始,前三行,前兩列。

7、適應iloc按位置單獨提起數據
df_inner.iloc[[0,2,5],[4,5]] #提取第0、2、5行,4、5列

8、使用ix按索引標籤和位置混合提取數據
df_inner.ix[:’2013-01-03’,:4] #2013-01-03號之前,前四列數據

9、判斷city列的值是否爲北京
df_inner[‘city’].isin([‘beijing’])

10、判斷city列裏是否包含beijing和shanghai,然後將符合條件的數據提取出來
df_inner.loc[df_inner[‘city’].isin([‘beijing’,’shanghai’])]

11、提取前三個字符,並生成數據表
pd.DataFrame(category.str[:3])

六、數據篩選
使用與、或、非三個條件配合大於、小於、等於對數據進行篩選,並進行計數和求和。

1、使用“與”進行篩選
df_inner.loc[(df_inner[‘age’] > 25) & (df_inner[‘city’] == ‘beijing’), [‘id’,’city’,’age’,’category’,’gender’]]

2、使用“或”進行篩選
df_inner.loc[(df_inner[‘age’] > 25) | (df_inner[‘city’] == ‘beijing’), [‘id’,’city’,’age’,’category’,’gender’]].sort([‘age’])

3、使用“非”條件進行篩選
df_inner.loc[(df_inner[‘city’] != ‘beijing’), [‘id’,’city’,’age’,’category’,’gender’]].sort([‘id’])

4、對篩選後的數據按city列進行計數
df_inner.loc[(df_inner[‘city’] != ‘beijing’), [‘id’,’city’,’age’,’category’,’gender’]].sort([‘id’]).city.count()

5、使用query函數進行篩選
df_inner.query(‘city == [“beijing”, “shanghai”]’)

6、對篩選後的結果按prince進行求和
df_inner.query(‘city == [“beijing”, “shanghai”]’).price.sum()

七、數據彙總
主要函數是groupby和pivote_table

1、對所有的列進行計數彙總
df_inner.groupby(‘city’).count()

2、按城市對id字段進行計數
df_inner.groupby(‘city’)[‘id’].count()

3、對兩個字段進行彙總計數
df_inner.groupby([‘city’,’size’])[‘id’].count()

4、對city字段進行彙總,並分別計算prince的合計和均值
df_inner.groupby(‘city’)[‘price’].agg([len,np.sum, np.mean])

八、數據統計
數據採樣,計算標準差,協方差和相關係數

1、簡單的數據採樣
df_inner.sample(n=3)

2、手動設置採樣權重
weights = [0, 0, 0, 0, 0.5, 0.5]
df_inner.sample(n=2, weights=weights)

3、採樣後不放回
df_inner.sample(n=6, replace=False)

4、採樣後放回
df_inner.sample(n=6, replace=True)

5、 數據表描述性統計
df_inner.describe().round(2).T #round函數設置顯示小數位,T表示轉置

6、計算列的標準差
df_inner[‘price’].std()

7、計算兩個字段間的協方差
df_inner[‘price’].cov(df_inner[‘m-point’])

8、數據表中所有字段間的協方差
df_inner.cov()

9、兩個字段的相關性分析
df_inner[‘price’].corr(df_inner[‘m-point’]) #相關係數在-1到1之間,接近1爲正相關,接近-1爲負相關,0爲不相關

10、數據表的相關性分析
df_inner.corr()

九、數據輸出
分析後的數據可以輸出爲xlsx格式和csv格式

1、寫入Excel
df_inner.to_excel(‘excel_to_python.xlsx’, sheet_name=’bluewhale_cc’)

2、寫入到CSV
df_inner.to_csv(‘excel_to_python.csv’)

十、測試代碼

# -*- coding: utf-8 -*-
"""
@author xiaofei
@email 
@auth
@desc 
"""
import time, json
import pandas as pd

data = [{"name": "skr", "value": 1}, {"name": "test", "value": 2}, {"name": "xi", "value": 3}]

res = pd.DataFrame(data)
print(res)

# 更改行名稱
res.rename(columns={'name': 'keyword', 'value': 'other_id'}, inplace=True)
print(res)

# 指定字段去重(保留第一個)
res.drop_duplicates(subset=['keyword'], keep='first', inplace=True)
print(res)

# 增加指定列
res['time'] = time.time()  # 全部賦固定值
print(res)
res['score'] = res['other_id'].map(lambda x: x + 1)  # 根據對應值改變
print(res)

# 更改指定列的類型
res['times'] = res['time'].astype('int')

# 刪除指定列
res.drop('time', axis=1, inplace=True)
print(res)

# 合併
data2 = [{"name": "skr", "Gender": 1}, {"name": "test", "Gender": 2}, {"name": "xi", "Gender": 1}, {"name": "fei"}]
res2 = pd.DataFrame(data2)
res2.rename(columns={'name': 'keyword'}, inplace=True)
print(res2)

## 這塊注意下, 以哪邊爲準很重要, 結果會差很多
result = pd.merge(res, res2, how='right', on='keyword').fillna(value=0)
result2 = pd.merge(res, res2, how='left', on='keyword').fillna(value=0)
print(result)
print(result2)

# 重置序列號index (可以在去重之後使用)
result2.reset_index()
print(result2)

# 格式轉換
datas = list(json.loads(result2.T.to_json()).values())
print(datas)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章