数据分析Pandas

什么是pandas

pandas 是基于一种 NumPy 的一种工具。NumPy 只能处理数值型的数据,但是 pandas 除了处理数值之外,还可以处理其它类型的数据。比如,字符串,时间序列等。

使用

Ⅰ. 数据结构

维数名称描述
1Series带标签的一维同构数组
2DataFrame带标签的,大小可变的,二维异构表格
一维Series
创建
import pandas as pd         
import numpy as np
t1 = pd.Series([1, 2, 3, 4])                                                                               
"""
0    1
1    2
2    3
3    4
dtype: int64
"""
t2 = pd.Series([1, 2, 3, 4, 5], index=list("abcde"))
"""
a    1
b    2
c    3
d    4
e    5
dtype: int64
""" 
dic = {"name" : "incipe", "age" : 0, "tel" : "xxxxxxxxxxx"}
t3 = pd.Series(dic)  
"""
name         incipe
age               0
tel     xxxxxxxxxxx
dtype: object
"""
t2.astype(float)
"""
0    1.0
1    2.0
2    3.0
3    4.0
4    5.0
dtype: float64
"""
t4 = pd.Series(np.arange(6))
"""
0    0
1    1
2    2
3    3
4    4
5    5
dtype: int64
"""
索引切片
t4[1]
# 1
t4[[1, 2, 3]]
"""
1    1
2    2
3    3
dtype: int64
"""
t4[1:5:2]
"""
1    1
3    3
dtype: int64
"""
t3["name"]
"""
'incipe'
"""
t3.index
# Index(['name', 'age', 'tel'], dtype='object')
t3.values
# array(['incipe', 0, 'xxxxxxxxxxx'], dtype=object)
二维DataFrame
t5 = pd.DataFrame(np.arange(12).reshape(3, 4)) 
"""
   0  1   2   3
0  0  1   2   3
1  4  5   6   7
2  8  9  10  11
"""
t6 = pd.DataFrame(np.arange(12).reshape(3, 4), index=list("abc"), columns=list("efgh"))
# index行索引,columns列索引
"""
   e  f   g   h
a  0  1   2   3
b  4  5   6   7
c  8  9  10  11
"""
dic = {"name" : ["incipe", "win"], "age" : [0, 0], "tel" : ["xxx", "xxx"]}
t7 = pd.DataFrame(dic)
"""
     name  age  tel
0  incipe    0  xxx
1     win    0  xxx
"""
l = [{"name" : "incipe"}, {"age" : 0}, {"tel" : "xxx"}]
t8 = pd.DataFrame(l)
"""
     name  age  tel
0  incipe  NaN  NaN
1     NaN  0.0  NaN
2     NaN  NaN  xxx
"""
t6.index
"""
Index(['a', 'b', 'c'], dtype='object')
"""
t6.columns
"""
Index(['e', 'f', 'g', 'h'], dtype='object')
"""
t6.values
"""
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11]])
"""
t6.shape
# (3, 4)
t6.dtypes
"""
e    int64
f    int64
g    int64
h    int64
dtype: object
"""
t6.describe()
"""
         e    f     g     h
count  3.0  3.0   3.0   3.0
mean   4.0  5.0   6.0   7.0
std    4.0  4.0   4.0   4.0
min    0.0  1.0   2.0   3.0
25%    2.0  3.0   4.0   5.0
50%    4.0  5.0   6.0   7.0
75%    6.0  7.0   8.0   9.0
max    8.0  9.0  10.0  11.0
""" 
t6.info()
"""
<class 'pandas.core.frame.DataFrame'>
Index: 3 entries, a to c
Data columns (total 4 columns):
 #   Column  Non-Null Count  Dtype
---  ------  --------------  -----
 0   e       3 non-null      int64
 1   f       3 non-null      int64
 2   g       3 non-null      int64
 3   h       3 non-null      int64
dtypes: int64(4)
memory usage: 120.0+ bytes
"""
t6.sort_values(by="h", ascending=False)
# 缺省ascending,默认按照升序排序
"""
   e  f   g   h
c  8  9  10  11
b  4  5   6   7
a  0  1   2   3
"""
索引切片
t6[:2] 
"""
   e  f  g  h
a  0  1  2  3
b  4  5  6  7
"""
t6["f"]
"""
a    1
b    5
c    9
Name: f, dtype: int64
"""

中括号里面是数字,表示对行进行操作,是字符串,表示对列进行操作,是列的索引。对行进行操作得到的依旧是DataFrame类型,对列进行操作,得到的是Series类型。

通过标签索引取数据。

t6.loc["a", "e"]
# 0
t6.loc["a", :]
"""
e    0
f    1
g    2
h    3
Name: a, dtype: int64
"""
t6.loc[:, "e"]
"""
a    0
b    4
c    8
Name: e, dtype: int64
"""
t6.loc[["a", "b"], :] 
"""
   e  f  g  h
a  0  1  2  3
b  4  5  6  7
"""
t6.loc[:, ["e", "f"]]
"""
   e  f
a  0  1
b  4  5
c  8  9
"""
t6.loc[["a", "b"], ["e", "f"]]
"""
   e  f
a  0  1
b  4  5
"""
t6.loc["a":"c", ["e", "f"]] 
# 这里的切片有点不同,最后一个元素是可以选中的
"""
   e  f
a  0  1
b  4  5
c  8  9
"""

通过位置获取数据。

t6.iloc[1: ,]
"""
e    4
f    5
g    6
h    7
Name: b, dtype: int64
"""
t6.iloc[:, 1]  
"""
a    1
b    5
c    9
Name: f, dtype: int64
"""
t6.iloc[[1, 2], [2, 3]]
"""
    g   h
b   6   7
c  10  11
"""

这里的取多行多列跟NumPy的有区别,在NumPy中,[[1, 2], [3, 4]]表示取第2行第3列的元素和第3行第5列的元素,构成了一个一维数组,而在pandas中,表述取第2行第4列的元素,第2行第5列的元素和第3行第4列的元素,第3行第5列的元素,组成一个DataFrame的二维数组。

布尔索引
t6 > 5
"""
       e      f      g      h
a  False  False  False  False
b  False  False   True   True
c   True   True   True   True
"""
t6[t6 > 5]
"""
     e    f     g     h
a  NaN  NaN   NaN   NaN
b  NaN  NaN   6.0   7.0
c  8.0  9.0  10.0  11.0
"""
t6[t6["e"] > 1]
"""
   e  f   g   h
b  4  5   6   7
c  8  9  10  11
"""

Ⅱ. 读取数据

pandas 提供了读取很多种文件的方法,比如:

  • 读取 csv pd.read_csv()
  • 读取 sql pd.read_sql()
  • 读取 excel pd.read_excel()
  • 读取 html pd.read_html()
  • 读取 json pd.read_json()

更多参考 pandas.pydata.org

Ⅲ. 字符串方法

方法描述
cat()拼接字符串,可以指定分隔符
contains()返回一个布尔矩阵表明是每个元素包含字符串或正则表达式
count()对出现符合的规则进行计数
endswith()、startswith()等价于str.startswith(pattern) 或者 str.endswith(pattern)
findall()返回每一个字串中出现的所有满足样式或正则的匹配
get()索引每一个元素(返回第i个元素)
join()使用传入的分隔符依次拼接每一个元素
len()计算字符串长度
lower()、upper()大小写转换
match()根据指定的正则表达式对元素进行re.match() 并以列表形式返回匹配到的组
pad()将白空格插入到字符串的左、右或者两端
center()等价于 pad(side="both")
repeat()值复制( s.str.repeat(3) 等价于x * 3)
replace()将匹配到的子串或正则表达式替换为另外的字符串,或者一个可调用对象的返回值
slice()将序列中的每一个字符串切片
split()基于分隔符切分字符串
strip()、rstrip()、lstrip()去掉空白符,包括换行符号

更多请参考 Pandas中文网

Ⅳ. 缺失数据处理

pandas 中,缺失数据会被定位为 NaN

  • 判断当前数据有没有 NaN pd.isnull(a), pd.notnull()
处理方法1

删除 NaN 所在的行列 dropna(axis=0, how='any', inplace=False)

参数:

  • axis 删除行还是列,0表示行,1表示列。
  • how 参数为 any 表示某行或者某列只要有一个 NaN 就删除,为 all 时某行某列要全为 NaN 才删除。
  • inplace 时候原地修改。
t7.DataFrame(np.arange(24).reshape(4, 6))
t7.index = list("abcd")
t7.columns = list("efghij")
t7.loc["a", "h"] = np.nan
t7.iloc[2, 2] = np.nan
"""
    e   f     g     h   i   j
a   0   1   2.0   NaN   4   5
b   6   7   8.0   9.0  10  11
c  12  13   NaN  15.0  16  17
d  18  19  20.0  21.0  22  23
"""
pd.isnull(t7)
"""
       e      f      g      h      i      j
a  False  False  False   True  False  False
b  False  False  False  False  False  False
c  False  False   True  False  False  False
d  False  False  False  False  False  False
"""
t7.dropna(axis=0) 
"""
    e   f     g     h   i   j
b   6   7   8.0   9.0  10  11
d  18  19  20.0  21.0  22  23
"""
处理方法2

填充数据 t.fillna(t.mean() t.fiallna(t.median()) t.fillna(0))

t7["h"].fillna(t7["h"].mean())
"""
a    15.0
b     9.0
c    15.0
d    21.0
Name: h, dtype: float64
"""
t7["g"].fillna(t7["g"].median())
"""
a     2.0
b     8.0
c     8.0
d    20.0
Name: g, dtype: float64
"""

Ⅴ. 统计方法

  • 获取不同字段的个数 unique()
  • 获取某行或某列或整个数组均值 mean()
  • 获取某行或某列中位数 median()
  • 获取某行或某列或整个数组信息 info()
  • 获取某行或某列或整个数组描述信息 desctibe()

Ⅵ. 数据合并

join() 把数据行索引相同的数据合并。

t1 = pd.DataFrame(np.ones((2, 4)), index=["A", "B"], columns=["a", "b", "c", "d"])
"""
     a    b    c    d
A  1.0  1.0  1.0  1.0
B  1.0  1.0  1.0  1.0
"""
t2 = pd.DataFrame(np.ones((3, 3)), index=list("ABC"), columns=list("xyz"))
"""
     x    y    z
A  1.0  1.0  1.0
B  1.0  1.0  1.0
C  1.0  1.0  1.0
"""
t1.join(t2)
"""
     a    b    c    d    x    y    z
A  1.0  1.0  1.0  1.0  1.0  1.0  1.0
B  1.0  1.0  1.0  1.0  1.0  1.0  1.0
"""
t2.join(t1)
"""
     x    y    z    a    b    c    d
A  1.0  1.0  1.0  1.0  1.0  1.0  1.0
B  1.0  1.0  1.0  1.0  1.0  1.0  1.0
C  1.0  1.0  1.0  NaN  NaN  NaN  NaN
"""

merge() 按照列索引进行数据合并

默认链接方式 inner 取交集,内连接

t3 = pd.DataFrame(np.zeros((2, 5)), index=list("qw"), columns=list("xjkhg"))
"""
     x    j    k    h    g
q  0.0  0.0  0.0  0.0  0.0
w  0.0  0.0  0.0  0.0  0.0
"""
t2.merge(t3)
"""
Empty DataFrame
Columns: [x, y, z, j, k, h, g]
Index: []
"""
t3.merge(t3)
"""
Empty DataFrame
Columns: [x, y, z, j, k, h, g]
Index: []
"""

因为没有相同的列,所以不能合并。

取并集 outer, 外连接

t2.merge(t3, left_on="x", right_on="x", how="outer")
"""
     x    y    z    j    k    h    g
0  1.0  1.0  1.0  NaN  NaN  NaN  NaN
1  1.0  1.0  1.0  NaN  NaN  NaN  NaN
2  1.0  1.0  1.0  NaN  NaN  NaN  NaN
3  0.0  NaN  NaN  0.0  0.0  0.0  0.0
4  0.0  NaN  NaN  0.0  0.0  0.0  0.0
"""
t4 = pd.DataFrame(np.arange(24).reshape(4, 6), index=list("yuio"), columns=list("xyjklp"))
"""
    x   y_x     j     k     l     p  y_y    z
0   0   1.0   2.0   3.0   4.0   5.0  NaN  NaN
1   6   7.0   8.0   9.0  10.0  11.0  NaN  NaN
2  12  13.0  14.0  15.0  16.0  17.0  NaN  NaN
3  18  19.0  20.0  21.0  22.0  23.0  NaN  NaN
4   1   NaN   NaN   NaN   NaN   NaN  1.0  1.0
5   1   NaN   NaN   NaN   NaN   NaN  1.0  1.0
6   1   NaN   NaN   NaN   NaN   NaN  1.0  1.0
"""

左连接 left 以左边的为准

t2.merge(t4, how="left")
# 以t2为准
"""
     x    y    z   j   k   l   p
0  1.0  1.0  1.0 NaN NaN NaN NaN
1  1.0  1.0  1.0 NaN NaN NaN NaN
2  1.0  1.0  1.0 NaN NaN NaN NaN
"""
t4.merge(t2, how="left")
# 以t4为准
"""
    x   y   j   k   l   p   z
0   0   1   2   3   4   5 NaN
1   6   7   8   9  10  11 NaN
2  12  13  14  15  16  17 NaN
3  18  19  20  21  22  23 NaN
"""

右连接 right

t4.merge(t2, how="right") 
"""
     x    y   j   k   l   p    z
0  1.0  1.0 NaN NaN NaN NaN  1.0
1  1.0  1.0 NaN NaN NaN NaN  1.0
2  1.0  1.0 NaN NaN NaN NaN  1.0
"""
t2.merge(t4, how="right")
"""
    x   y   z   j   k   l   p
0   0   1 NaN   2   3   4   5
1   6   7 NaN   8   9  10  11
2  12  13 NaN  14  15  16  17
3  18  19 NaN  20  21  22  23
"""

Ⅶ. 分组聚合

groupby(by="columns_name")

返回值得到一个 DataFrameGroupBy 对象。

也可以按照多列进行分组,参数传个列表进去就好了 groupby(by=["columns_name1", "columns_name2"])

l = [{"Country" : "CN", "Custom" : "xxx"}, {"Country" : "ZA", "Custom" : "xxx1"}, {"Country" : "UK", "Custom" : "xxx2"}, {"Country" : "US", "Custom" : "xxx3"}] 
df = pd.DataFrame(l)
"""
  Country Custom
0      CN    xxx
1      ZA   xxx1
2      UK   xxx2
3      US   xxx3
"""
group = df.groupby("Country") 
"""
<pandas.core.groupby.generic.DataFrameGroupBy object at 0x7f92edc33940>
"""
for i in group: 
    print(i) 
    print("*" * 10) 
"""
('CN',   Country Custom
0      CN    xxx)
**********
('UK',   Country Custom
2      UK   xxx2)
**********
('US',   Country Custom
3      US   xxx3)
**********
('ZA',   Country Custom
1      ZA   xxx1)
**********
"""
for i, j in group: 
    print(i) 
    print("-" * 10) 
    print(j) 
    print("*" * 10)
"""
CN
----------
  Country Custom
0      CN    xxx
**********
UK
----------
  Country Custom
2      UK   xxx2
**********
US
----------
  Country Custom
3      US   xxx3
**********
ZA
----------
  Country Custom
1      ZA   xxx1
**********
"""

按照 column_name 进行分组,得到的是一个元组,第一个字段是 column_name 名字,第二个字段是这个 column_nameDataFrame

聚合方法

group.count()
"""
Country        
CN            1
UK            1
US            1
ZA            1
"""

数据量太小了,展示效果不好。

除了前面提到的统计方法可以作为聚合方法,还有更多聚合方法:

  • std()、var() 无偏(分母为n - 1)标准差和方差。
  • min()、max() 最大最小值。

Ⅷ. 时间序列

pd.date_range(start=None, end=None, periods=None, freq='D')

date = pd.date_range(start="20000131", end="20000215", freq="D") 
"""
DatetimeIndex(['2000-01-31', '2000-02-01', '2000-02-02', '2000-02-03',
               '2000-02-04', '2000-02-05', '2000-02-06', '2000-02-07',
               '2000-02-08', '2000-02-09', '2000-02-10', '2000-02-11',
               '2000-02-12', '2000-02-13', '2000-02-14', '2000-02-15'],
              dtype='datetime64[ns]', freq='D')
"""
date = pd.date_range(start="20000131", end="20000215", freq="10D")
"""
DatetimeIndex(['2000-01-31', '2000-02-10'], dtype='datetime64[ns]', freq='10D')
"""
date = pd.date_range(start="20000131", periods=10, freq="D")
"""
DatetimeIndex(['2000-01-31', '2000-02-01', '2000-02-02', '2000-02-03',
               '2000-02-04', '2000-02-05', '2000-02-06', '2000-02-07',
               '2000-02-08', '2000-02-09'],
              dtype='datetime64[ns]', freq='D')
"""

freq 选值pandas中文

总结

数据分析简单的一些概要就到这里了。以后可能会有更为详细的介绍和用法。

数据太多,人都傻了。

数据可视化matplotlib

科学计算NumPy

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值