1. 程式人生 > >Python Dataframe遍歷,刪除,初始化操作

Python Dataframe遍歷,刪除,初始化操作

建立一個DataFrame,它有幾種建立方式:

列表,序列(pandas.Series), numpy.ndarray的字典
二維numpy.ndarray
別的DataFrame
結構化的記錄(structured arrays)
其中,我最喜歡的是通過二維ndarray建立DataFrame,因為程式碼敲得最少:

import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.randn(3, 4))
df
0 1 2 3
0 0.236175 -0.394792 -0.171866 0.304012
1 0.651926 0.989046 0.160389 0.482936
2 -1.039824 0.401105 -0.492714 -1.220438

當然你還可以參考我的這篇文章從mysql資料庫或者csv檔案中載入資料到dataframe。
dataframe中index用來標識行,column標識列,shape表示維度。

df.index
df.columns
df.shape

通過describe方法,我們可以對df中的資料有個大概的瞭解:

df.describe()
0 1 2 3
count 3.000000 3.000000 3.000000 3.000000
mean -0.050574 0.331786 -0.168064 -0.144496
std 0.881574 0.694518 0.326568 0.936077
min -1.039824 -0.394792 -0.492714 -1.220438
25% -0.401824 0.003156 -0.332290 -0.458213
50% 0.236175 0.401105 -0.171866 0.304012
75% 0.444051 0.695076 -0.005739 0.393474
max 0.651926 0.989046 0.160389 0.482936

資料select, del, update。

按照列名select:


df[0]
 
0 0.236175
1 0.651926
2 -1.039824

按照行數select:

df[:3] #選取前3行
按照索引select:
df.loc[0]
 
0 0.236175
1 -0.394792
2 -0.171866
3 0.304012

按照行數和列數select:

df.iloc[3] #選取第3行
df.iloc[2:4] #選取第2到第3行
df.iloc[0,1] #選取第0行1列的元素
dat.iloc[:2, :3] #選取第0行到第1行,第0列到第2列區域內的元素
df1.iloc[[1,3,5],[1,3]] #選取第1,3,5行,第1,3列區域內的元素

刪除某列:

del df[0]
df
1 2 3
0 -0.394792 -0.171866 0.304012
1 0.989046 0.160389 0.482936
2 0.401105 -0.492714 -1.220438

刪除某行:

df.drop(0)
 
1 2 3
1 0.989046 0.160389 0.482936
2 0.401105 -0.492714 -1.220438

運算。

基本運算:

df[4] = df[1] + df[2]
 
1 2 3 4
0 -0.394792 -0.171866 0.304012 -0.566659
1 0.989046 0.160389 0.482936 1.149435
2 0.401105 -0.492714 -1.220438 -0.091609

map運算,和python中的map有些類似:

df[4].map(int)
0 0
1 1
2 0

apply運算:

df.apply(sum)
 
1 0.995359
2 -0.504192
3 -0.433489
4 0.491167

Group by 操作。

pandas中的group by 操作是我的最愛,不用把資料匯入excel或者mysql就可以進行靈活的group by 操作,簡化了分析過程。

df[0] = ['A', 'A', 'B']
df
 
1 2 3 4 0
0 -0.394792 -0.171866 0.304012 -0.566659 A
1 0.989046 0.160389 0.482936 1.149435 A
2 0.401105 -0.492714 -1.220438 -0.091609 B
 
g = df.groupby([0])
 
g.size()
 
A 2
B 1
 
g.sum()
 
1 2 3 4
0
A 0.594254 -0.011478 0.786948 0.582776
B 0.401105 -0.492714 -1.220438 -0.091609
groupby選擇列和迭代
g = df.groupby(df['artist_id'])
gsize=g.size()
aa=g.sum()

匯出到csv檔案

dataframe可以使用to_csv方法方便地匯出到csv檔案中,如果資料中含有中文,一般encoding指定為”utf-8″,否則匯出時程式會因為不能識別相應的字串而丟擲異常,index指定為False表示不用匯出dataframe的index資料。

df.to_csv(file_path, encoding='utf-8', index=False)

作者:Deep_IT
來源:CSDN
原文:https://blog.csdn.net/wang4959520/article/details/51087957
版權宣告:本文為博主原創文章,轉載請附上博文連結!