Pandas使用(二)

DataFrame介紹

DataFrame表示的是矩陣的數據表,它包含已排序的列集合,每一列可以是不同的值類型(數值,字符串布爾值)。在DataFrame中,數據被存儲爲一個以上的二維塊

img

DataFrame創建

在這裏插入圖片描述

pd.DataFrame(data=None, index=None, columns=None, dtype=None, copy=False)

  • data : 爲創建數組的數據,可爲ndarry,dict
  • index : 指定行索引 0軸
  • colums : 指定爲列索引 1軸
  • dtype : 數組數據類型
  • copy : 是否拷貝
  • 注意 :(Nan爲浮點類型)
# 創建出DataFrame的數組
In [22]: data1 = pd.DataFrame(data=np.arange(12).reshape(3,4))

In [23]: data1
Out[23]:
   0  1   2   3
0  0  1   2   3
1  4  5   6   7
2  8  9  10  11

# index 爲行索引
In [24]: data1.index
Out[24]: RangeIndex(start=0, stop=3, step=1)

# Colum 爲列索引
In [25]: data1.columns
Out[25]: RangeIndex(start=0, stop=4, step=1)

# 創建出數組,index爲0軸,columns爲1軸

In [29]: data = pd.DataFrame(np.arange(12).reshape(3,4),index=['a','b','c'],columns=['a','b'
    ...: ,'c','d'])

In [30]: data
Out[30]:
   a  b   c   d
a  0  1   2   3
b  4  5   6   7
c  8  9  10  11

當指定columns沒有數據時

In [46]: data = {
    'name': ['SmallJ', 'SenvenJ'],
    'age': [18, 20]
}
    
# 當指定的列索引沒有值的時候,顯示的結果爲Nan
# 指定列索引時,如果指定的列索引不在對應的字典數據當中 則會自動填充爲Nan

In [47]: data = pd.DataFrame(data,columns=['name','age','gender'])

In [48]: data
Out[48]:
      name  age gender
0   SmallJ   18    NaN
1  SenvenJ   20    NaN

當數據不齊全的時候

In [52]: data = [{'name':'Small','age':18},{'name':'SenvenJ','gender':'男'},{'name':'Small_J','age':20,'gender':'男'}]

In [53]: data
Out[53]:
[{'name': 'Small', 'age': 18},
 {'name': 'SenvenJ', 'gender': '男'},
 {'name': 'Small_J', 'age': 20, 'gender': '男'}]

# 當數據不齊全的時候顯示的值爲Nan
In [54]: data = pd.DataFrame(data)

In [55]: data
Out[55]:
      name   age gender
0    Small  18.0    NaN
1  SenvenJ   NaN      男
2  Small_J  20.0

當想查看數組類型的時候直接調用其查看

In [56]: # 查看name的數組類型

In [57]: data.name
Out[57]:
0      Small
1    SenvenJ
2    Small_J
Name: name, dtype: object

In [58]: # 查看age數組類型

In [60]: data.age
Out[60]:
0    18.0
1     NaN
2    20.0
Name: age, dtype: float64

In [61]: # 查看gender數組類型

In [62]: data.gender
Out[62]:
0    NaN
12      男
Name: gender, dtype: object

DataFrame基礎操作

  • df.shape

    • 查看數組形狀,返回值爲元組
  • df.dtypes

    • 查看列數據類型
  • df.ndim

    • 數組維度,返回爲整數
  • df.index

    • 行索引
  • df.columns

    • 列索引
  • df.drop(columns=[‘name’,‘age’],inplace=False)

    • 返回被刪除之後的DataFrame

    • inplace : 默認情況下爲False,當爲True時,對原數組進行修改

In [9]: data = [{'name':'Small','age':18},{'name':'SenvenJ','gender':'男'},{'name':'Small_J','age':20,'gender':'男'}]
    
In [10]: # 查看數組的形狀

In [11]: data.shape
Out[11]: (3, 3)

In [12]: # 查看數據的類型

In [13]: data.dtypes
Out[13]:
name       object
age       float64
gender     object
dtype: object

In [14]: # 查看數據的維度

In [15]: data.ndim
Out[15]: 2

In [16]: # 查看索引

In [17]: data.index
Out[17]: RangeIndex(start=0, stop=3, step=1)

In [18]: # 查看列索引

In [19]: data.columns
Out[19]: Index(['name', 'age', 'gender'], dtype='object')

In [20]: data
Out[20]:
      name   age gender
0    Small  18.0    NaN
1  SenvenJ   NaN      男
2  Small_J  20.0      男

In [21]: data.drop(index=0)   # 刪除索引爲0行
Out[21]:
      name   age gender
1  SenvenJ   NaN      男
2  Small_J  20.0      男

In [22]: data
Out[22]:
      name   age gender
0    Small  18.0    NaN
1  SenvenJ   NaN      男
2  Small_J  20.0      男

In [23]: data.drop(index=0)   # 刪除索引爲0行,但並不會指定刪除
Out[23]:
      name   age gender
1  SenvenJ   NaN      男
2  Small_J  20.0

In [27]: data
Out[27]:
      name   age gender
0    Small  18.0    NaN
1  SenvenJ   NaN      男
2  Small_J  20.0# inplace對原數據進行修改,指定爲行索引
In [28]: data.drop(index=0,inplace=True)

In [29]: data
Out[29]:
      name   age gender
1  SenvenJ   NaN      男
2  Small_J  20.0# 指定爲列索引,對原數據進行修改
In [32]: data.drop(columns='gender',inplace=True)

In [33]: data
Out[33]:
      name   age
1  SenvenJ   NaN
2  Small_J  20.0

DataFrame查詢

  • d.head(n)
    • 顯示頭部幾行,默認情況下爲前五行
  • d.tail(n)
    • 顯示末尾幾行,默認後五行
  • d.info()
    • 相關信息概述

讀取之前抓取的數據

In [47]: read_data = pd.read_csv(r'D:\爬蟲\豆瓣手機版\douban.csv')

In [48]: # 默認情況下讀取的行數爲五行,可以指定行數

In [49]: read_data.head(3)
Out[49]:
       title                                          title_jpg  score
0  指環王1:魔戒再現  https://img3.doubanio.com/view/photo/s_ratio_p...    9.0
1        七宗罪  https://img9.doubanio.com/view/photo/s_ratio_p...    8.8
2      瘋狂的石頭  https://img3.doubanio.com/view/photo/s_ratio_p...    8.5

In [50]: # 讀取末尾的數據

In [51]: read_data.tail()
Out[51]:
      title                                          title_jpg  score
45  愛在黎明破曉前  https://img9.doubanio.com/view/photo/s_ratio_p...    8.8
46     婚姻故事  https://img1.doubanio.com/view/photo/s_ratio_p...    8.6
47  穿普拉達的女王  https://img9.doubanio.com/view/photo/s_ratio_p...    8.1
48    搏擊俱樂部  https://img1.doubanio.com/view/photo/s_ratio_p...    9.0
49     火星救援  https://img3.doubanio.com/view/photo/s_ratio_p...    8.4
    
    # 查看相關的數據描述
In [53]: read_data.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 50 entries, 0 to 49
Data columns (total 3 columns):
title        50 non-null object
title_jpg    50 non-null object
score        50 non-null float64
dtypes: float64(1), object(2)
memory usage: 1.3+ KB

練習

# @Time : 2020/5/9 13:55 
# @Author : SmallJ

import numpy as np
import pandas as pd

# 取前兩行


data = pd.read_csv(r'catNames2.csv')

# print(data)
# 取前兩行
# print(data[:3])

# 取出Count_AnimalName
# print(data['Count_AnimalName'])

# Row_Labels前兩行
# print(data['Row_Labels'][:2])

# 找到所有的使用次數超過800的貓的名字
# print(data[data['Count_AnimalName'] > 800])

# 返回的結果爲行數的總和
# print(len(data['Row_Labels']))

# 找到所有的使用次數超過700並且名字的字符串的長度大於4的狗的名字
# data['Row_Labels'].str.len()>4 該返回的爲布爾類型
# 在Pandas中不能使用Python的關鍵字and來進行操作,所以使用&來進行操作
# 還需要使用括號包裹起來條件
print(data[(data['Count_AnimalName'] > 700) & (data['Row_Labels'].str.len() > 4)])

DateFrame索引

類型 描述
df[:位置索引] 或 df[:“標籤索引”] 表示對行操作
df[“列索引”] 或df[[“列索引”,“列索引”]] 表示對列進行操作

Pandas字符串的常用方法

方法 描述
df.str.contains() 返回表示各字符串是否含義指定模式的布爾型數組
df.str.len() 返回各字符串的長度
df.str.lower() 將各字符串全轉爲小寫
df.str.upper() 將各字符串全轉爲小寫或大寫
df.str.slice() 對series中的各個字符串進行子串截取
df.str.split() 根據分隔符或正則表達式對字符串進行拆分

使用loc及iloc選擇數據

  • df.loc[] : 通過軸標籤選擇數據
  • df.iloc[] : 通過整數(位置)標籤選擇數據
類型 描述
df.loc[val] 根據標籤索引選擇DataFrame的單行或多行
df.loc[:,val] 根據標籤索引選擇DataFrame的單列或多列
df.loc[val1,val2] 同時選擇行和列的一部分
df.iloc[where] 根據位置索引選擇DataFrame的單行或多行
df.iloc[:,where] 根據位置索引選擇DataFrame的單行或多列
df.iloc[where_i,where_j] 根據位置索引選擇行和列
# @Time : 2020/5/9 16:31 
# @Author : SmallJ

import numpy as np
import pandas as pd

data = [
    {'book': 'Python爬蟲開發', 'press': '北京大學出版社', 'score': 89.5},
    {'book': 'Python數據分析', 'press': '工業大學出版社', 'score': 101.5},
    {'book': 'PythonWeb開發', 'press': '廣西大學出版社', 'score': 301.5},
    {'book': 'Python人工智能', 'press': '北京大學出版社', 'score': 505.5}
]

read_data = pd.DataFrame(data, index=['a', 'b', 'c', 'd'])
# print(read_data)

# loc 是根據標籤索引來取值
# iloc 是根據index索引來取值

# loc 標籤值不會根據左閉右開的來進行操作
# 取標籤b 到 d 兩行數據
print(read_data.loc['b':'d'])

# 取標籤b和d兩行數據,採用神奇索引
print(read_data.loc[['b', 'd']])

# iloc 是根據索引進行操作
# 取索引 左閉右開的原則
# 取0到3索引的數據
print(read_data.iloc[0:3])

# 取0到3索引數據的’book‘書
print(read_data.iloc[0:3]['book'])

# 取0到3索引數據的’book‘和'score'書
print(read_data.iloc[0:3][['book', 'score']])

注意

​ Pandas中可以直接賦值np.nan, 且賦值當前列數據會自動轉爲浮點類型。而不是整個數組都轉,這主要是因爲Pandas數據可以是異質性。

# @Time : 2020/5/10 0:59 
# @Author : SmallJ 

import pandas as pd
import numpy as np

data = pd.DataFrame(np.arange(12).reshape(3, 4))

# np.nan能對數據進行修改
data.iloc[0, 0] = np.nan
print(data)
     0  1   2   3
0  NaN  1   2   3
1  4.0  5   6   7
2  8.0  9  10  11

DataFrame算術

實際上,通過 + - * / // ** 等符號可以直接對DataFrame與DataFrame之間或者DataFrame以及Series之間進行運算。但秉承的原則就是對應索引運算,存在索引不同時,返回結果爲索引對的並集。

但是實際操作會發現,當存在索引不同時,返回的值自動填充NaN

使用填充Nan的方法

方法 描述
add 加法(+)
sub 減法(-)
div 除法(/)
floordiv 整除(//)
mul 乘法(*)
pow 冪次方(**)
In [1]: import numpy as np

In [2]: import pandas as pd

In [4]: df1 = pd.DataFrame(np.ones((2,2)),columns=list("AB"))

In [5]: df2 = pd.DataFrame(np.ones((3,3)),columns=list("ABC"))

In [6]: # 當進行數組相加時

In [7]: df1 + df2
Out[7]:
     A    B   C
0  2.0  2.0 NaN
1  2.0  2.0 NaN
2  NaN  NaN NaN

In [8]: df1.shape
Out[8]: (2, 2)

In [9]: df2.shape
Out[9]: (3, 3)

In [10]: # 對應的數值進行相加,當數組沒有對應時,填充nan值

當二維數組跟一維數組進行相加時

In [11]: df1
Out[11]:
     A    B
0  1.0  1.0
1  1.0  1.0

In [12]: df2
Out[12]:
     A    B    C
0  1.0  1.0  1.0
1  1.0  1.0  1.0
2  1.0  1.0  1.0

In [13]: s1 = df2.iloc[0]

In [14]: s1
Out[14]:
A    1.0
B    1.0
C    1.0
Name: 0, dtype: float64

In [15]: # 當一維數組跟二維數組進行相加時

In [16]: df2 + s1
Out[16]:
     A    B    C
0  2.0  2.0  2.0
1  2.0  2.0  2.0

In [17]: # 當一維數組跟二維數組進行相加時,會對應每個值都進行相加
In [17]: df1 + df2
Out[17]:
     A    B   C
0  2.0  2.0 NaN
1  2.0  2.0 NaN
2  NaN  NaN NaN

In [18]: df1.add??
Signature: df1.add(other, axis='columns', level=None, fill_value=None)
Docstring:
Get Addition of dataframe and other, element-wise (binary operator `add`).

Equivalent to ``dataframe + other``, but with support to substitute a fill_value
for missing data in one of the inputs. With reverse version, `radd`.

Among flexible wrappers (`add`, `sub`, `mul`, `div`, `mod`, `pow`) to
arithmetic operators: `+`, `-`, `*`, `/`, `//`, `%`, `**`.

Parameters
----------
other : scalar, sequence, Series, or DataFrame
    Any single or multiple element data structure, or list-like object.
axis :  {0 or 'index', 1 or 'columns'}
    Whether to compare by the index (0 or 'index') or columns
    (1 or 'columns'). For Series input, axis to match Series index on.
level : int or label
    Broadcast across a level, matching Index values on the
    passed MultiIndex level.
fill_value : float or None, default None
    Fill existing missing (NaN) values, and any new element needed for
    successful DataFrame alignment, with this value before computation.
    If data in both corresponding DataFrame locations is missing
    the result will be missing.

Returns
-------
DataFrame
    Result of the arithmetic operation.

See Also
--------
DataFrame.add : Add DataFrames.
DataFrame.sub : Subtract DataFrames.
DataFrame.mul : Multiply DataFrames.
DataFrame.div : Divide DataFrames (float division).
DataFrame.truediv : Divide DataFrames (float division).
DataFrame.floordiv : Divide DataFrames (integer division).
DataFrame.mod : Calculate modulo (remainder after division).
DataFrame.pow : Calculate exponential power.

# fill_value 爲填充值的意思
# 填充值會在缺失值上進行
# 當我fill_value 填3的時候爲什麼顯示4呢
# 原因在於:填充值相當與是把nan填充爲3但還是要進行下一步的運算
In [19]: df1.add(df2,fill_value=3)
Out[19]:
     A    B    C
0  2.0  2.0  4.0
1  2.0  2.0  4.0
2  4.0  4.0  4.0

注意

  • Series使用算術方法,不支持指定填充值

DataFrame排序

df.sort_index()

參數 說明
axis {0 or ‘index’, 1 or ‘columns’}, default 0,默認按照列排序,即縱向排序;如果爲1,則是橫向排序。
ascending 默認情況下爲True升序
# @Time : 2020/5/10 1:52 
# @Author : SmallJ 

import numpy as np
import pandas as pd

data = pd.DataFrame(np.arange(12).reshape(3, 4), index=list('abc'))

# axis指定軸,默認0軸
# ascending爲排序方式,默認爲True表示升序

# sort_index中的ascending的降序和升序主要是看標籤的值來決定
# 當標籤的值爲數字時,返回就是按數字大小進行排序
# 當標籤的值爲字母時,返回的值是按照ascii值來進行排序
data = data.sort_index(ascending=False)
# print(data)

#   0  1   2   3
# c  8  9  10  11
# b  4  5   6   7
# a  0  1   2   3

# 當指定爲axis軸爲1時,按軸的數字進行排序
data = data.sort_index(axis=1, ascending=False)
print(data)

df.sort_values(by)

參數 說明
by 指定列名(axis=0或’index’)或索引值(axis=1或’columns’)
axis 若axis=0或’index’,則按照指定列中數據大小排序;若axis=1或’columns’,則按照指定索引中數據大小排序,默認axis=0
ascending 是否按指定列的數組升序排列,默認爲True,即升序排列
inplace 是否用排序後的數據集替換原來的數據,默認爲False,即不替換
na_position {‘first’,‘last’},設定缺失值的顯示位置
#利用字典dict創建數據框
import numpy as np
import pandas as pd
df=pd.DataFrame({'col1':['A','A','B',np.nan,'D','C'],
                 'col2':[2,1,9,8,7,7],
                 'col3':[0,1,9,4,2,8]
})
print(df)

>>>
  col1  col2  col3
0    A     2     0
1    A     1     1
2    B     9     9
3  NaN     8     4
4    D     7     2
5    C     7     8
#依據第一列排序,並將該列空值放在首位
print(df.sort_values(by=['col1'],na_position='first'))
>>>
  col1  col2  col3
3  NaN     8     4
0    A     2     0
1    A     1     1
2    B     9     9
5    C     7     8
4    D     7     2
#依據第二、三列,數值降序排序
print(df.sort_values(by=['col2','col3'],ascending=False))
>>>
  col1  col2  col3
2    B     9     9
3  NaN     8     4
5    C     7     8
4    D     7     2
0    A     2     0
1    A     1     1
#根據第一列中數值排序,按降序排列,並替換原數據
df.sort_values(by=['col1'],ascending=False,inplace=True,
                     na_position='first')
print(df)
>>>
  col1  col2  col3
3  NaN     8     4
4    D     7     2
5    C     7     8
2    B     9     9
1    A     1     1
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章