Pandas的DataFrame

1. 手工建立DataFrameapp

1 a = [[1, 2, 2],[3,None,6],[3, 7, None],[5,None,7]]
2 data = DataFrame(a)

 2. Excel數據數據沒有頂頭的處理函數

 1 import os
 2 import pandas as pd
 3 base_path = "D:\\practicespace\\Python\\datasets"
 4 file_name = "data.xlsx"
 5 path = os.path.join(base_path, file_name)
 6 print(path)
 7 if(os.path.exists(path)):
 8     print("file exists")
 9 
10 data = pd.read_excel(path, sheet_name="Sheet4", header=2, usecols="C:J")
11 data.head()

 

3. 字段值統計oop

 data.Region.value_counts() 優化

output:spa

EOC    36675.net

SOC    28468excel

WOC    20460code

NOC    16017blog

Name: Region, dtype: int64索引

4.字段包含特殊符號(好比空格)的索引方式

不能再採用".字段名「的方式,而是要採用字符索引方式:

1 print("region count: ", len(data.Region.value_counts()))
2 print("Sub Region count: ", len(data["Sub Region"].value_counts()))

 

或者去掉特殊,而後再進行字段直接索引

df = df.rename(columns=lambda x: x.replace("'","").replace('"','')).replace(" ","")

 

5. 缺失值處理

1)統計缺失值

1 total = data.isnull().sum().sort_values(ascending=True)
2 percent = (data.isnull().sum()/data.isnull().count()).sort_values(ascending=True)
3 table = pd.concat([total, percent], axis=1, keys=["total", "percent"])

 

2)刪除缺失值的行列

1 # 使用dropna方法刪除含有缺失值的行,默認是行
2 print(data.dropna())
3 # 刪除含有缺失值的列
4 print(data.dropna(axis=1))

 

3)填充缺失值

 1 from pandas import DataFrame
 2 a = [[1, 2, 2],[3,None,6],[3, 7, None],[5,None,7]]
 3 data = DataFrame(a)
 4 print(data)
 5 # 統一填充缺失值爲指定值
 6 print(data.fillna(0))
 7 # index=1(從0開始)列缺失值填充爲1,index=2的列的缺失值填充爲2
 8 print(data.fillna({1:1,2:2}))
 9 # 使用平均值進行填充
10 print(data.fillna(data.mean()))
11 # 前向填充,使用默認是上一行的值,設置axis=1能夠使用列進行填充,不存在或者上一行也是None的時候就不填充
12 print(data.fillna(method="ffill"))
13 print()
14 # 後向填充,使用下一行的值,不存在或者下一行也是None的時候就不填充
15 print(data.fillna(method="bfill"))

 

6.遍歷數據運算

 1 # 最原始,效率最低的迭代方案
 2 def myfunction(df):
 3     res_list = []
 4     for i in range(0,len(df)):
 5         res_list.append(df.iloc[i]['first']/df.iloc[i][‘second'])
 6     return disftance_list
 7 # 經過iterrows作遍歷
 8 def haversine_looping(df):
 9     disftance_list = []
10     for index,row in df.iterrows():
11         disftance_list.append(row[‘high']/row[‘open'])
12     return disftance_list
13 # Cython作了全局優化,效率比iterrow有所提升,這裏注意axis必需要設置
14 df.apply(lambda row: row[‘high']/row[‘open'], axis =1)
15 # pandas的矢量化處理,比較快,作了底層實現優化
16 dftest4['rate'] = dftest4['high']/dftest4['open']
17 # 經過values將pandas的serias數據轉化爲numpy arrays,效率最高,由於numpy在底層作了C的預編譯
18 dftest5['rate'] = dftest5['high'].values/dftest5['open'].values

 

7. 列內容重置

1 df1['total'] = df1.Jan + df1.Feb + df1.Mar
2 df1['category'] = np.where(df1['total'] > 200000, 'A', 'B')

 

這裏注意,若是是total已經存在,能夠經過df1.total的索引方式,可是若是是新建立的列,只能經過["columnName"]的方式進行索引。

8. 刪除列

1 del DF['column-name']
2 DF= DF.drop('column_name', 1);
3 DF.drop('column_name',axis=1, inplace=True)
4 DF.drop([DF.columns[[0,1, 3]]], axis=1,inplace=True)   # Note: zero indexed

 

9. group

在pandas裏面的group,分組和運算是分開的,對於聚合則是在group以後經過調用sum,mean之類的函數基於分組作運算;

1 # 單分組
2 groupall = data.groupby("Region")
3 groupall = groupall.sum()
4 groupall
5 # 多分組
6 groupall = data.groupby(["Region", "Sub Region"])
7 groupall = groupall.sum()
8 groupall

 

參考:

https://www.jianshu.com/p/e664b9a3bf70

https://blog.csdn.net/katyusha1/article/details/81501893

缺失值處理

https://blog.csdn.net/sinat_29957455/article/details/79017363

迭代處理

https://blog.csdn.net/m0_37382341/article/details/83716988

 

 

 

 

 

 

 

 

 

相關文章
相關標籤/搜索