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
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章