数据分析—数据处理工具pandas(二)

导读:本篇文章讲解 数据分析—数据处理工具pandas(二),希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com

数据分析—数据处理工具pandas(二)

一、Pandas数据结构Dataframe:基本概念及创建

1.DataFrame简介

Dataframe是一个表格型的数据结构,“带有标签的二维数组”。
Dataframe带有index(行标签)和columns(列标签)
DataFrame的每一列相当于一个Series,列名就是Series.name
eg:

import pandas as pd
import numpy as np
data = {
    'name': ['Mary', 'Jack'],
    'age': [12, 18],
    'sex': ['女', '男']
}
frame = pd.DataFrame(data)
print(frame)
print(frame.index)  # 行标签
print(frame.columns) # 列标签
print(frame.values)  # 查看值,为二维数组

# 可以通过index  column 更改行/列标签
frame.index = ['a', 'b']   # frame = pd.DataFrame(data, index=['a', 'b'])
print(frame)

# 结果:
   name  age sex
0  Mary   12   女
1  Jack   18   男
RangeIndex(start=0, stop=2, step=1)
Index(['name', 'age', 'sex'], dtype='object')
[['Mary' 12 '女']
 ['Jack' 18 '男']]
   name  age sex
a  Mary   12   女
b  Jack   18   男
2.创建Dataframe
(1)方法一:由数组/list组成的字典
# 由数组/list组成的字典 创建Dataframe,columns为字典key,index为默认数字标签

data1 = {
    'name': ['Mary', 'Jack'],
    'age': [12, 18],
    'sex': ['女', '男']
}
frame1 = pd.DataFrame(data1)
print(frame1)
print('----')
data2 = {
    'one': np.arange(2),     
    'tow': np.arange(10, 12) # 注意列必须与前面保持一致,故nparange(10, 13) 有三个元素,不行,会运行错误
}   
frame2 = pd.DataFrame(data2)
print(frame2)

# columns参数:可以【重新指定】列的顺序,格式为list,如果现有数据中没有该列(比如'd'),则产生NaN值
d1 = pd.DataFrame(data1, columns=['sex', 'name', 'age', 'd'])  # cpolumn只是改变已有的列顺序,不能改变成设置的列,但是index可以
print(d1)
# 如果columns重新指定时候,列的数量可以少于原数据,但是这样只会生成你指定的列
d2 = pd.DataFrame(data1, columns=['sex'])  # 只会有sex这一列
print(d2)

# index参数:重新定义index,格式为list,长度必须保持一致
d3 = pd.DataFrame(data1, index=['a', 'b'])
print(d3) 

# 结果:
   name  age sex
0  Mary   12   女
1  Jack   18   男
----
   one  tow
0    0   10
1    1   11
  sex  name  age    d
0   女  Mary   12  NaN
1   男  Jack   18  NaN
  sex
0   女
1   男
   name  age sex
a  Mary   12   女
b  Jack   18   男

小结:
1.用列表/数组组成的字典生成DataFrame必须保证value的长度一致
2.column只能用来重新只是改变已有的列顺序,不能改变成设置的列

(2)方法二:由Series组成的字典
# 由Seris组成的字典 创建Dataframe,columns为字典key,index为Series的标签(如果Series没有指定标签,则是默认数字标签)

# 没有设置index的Series
data1 = {'one':pd.Series(np.random.rand(2)),
        'two':pd.Series(np.random.rand(3))
}  
df1 = pd.DataFrame(data1)
print(df1)

# 设置了Series的下标
data2 = {'one':pd.Series(np.arange(2), index=['a', 'b']),
        'two':pd.Series(np.arange(100, 103), index=['d', 'b', 'c'])
}
df2 = pd.DataFrame(data2)
print(df2)

# 结果:
        one       two
0  0.173666  0.578512
1  0.952062  0.601752
2       NaN  0.933093
   one    two
a  0.0    NaN
b  1.0  101.0
c  NaN  102.0
d  NaN  100.0

小结:用Series生成DataFrame,其中Series的长度可以不一致。会取长的为行数,然后不足的用NaN补充

(3)方法三:通过二维数组直接创建
ar = np.arange(20, 30).reshape(2, 5)
print(ar)
f1 = pd.DataFrame(ar)
print(f1)
print('-----')
f2 = pd.DataFrame(ar, index=['a', 'b'], columns=list('qwert'))  # column的元素个数必须与二维数组列数相同
print(f2)

# 结果:
[[20 21 22 23 24]
 [25 26 27 28 29]]
    0   1   2   3   4
0  20  21  22  23  24
1  25  26  27  28  29
-----
    q   w   e   r   t
a  20  21  22  23  24
b  25  26  27  28  29
(4)方法四:由字典组成的列表
d = [{'one': 1, 'two': 2}, {'one': 11, 'two': 12, 'three': 13}]  # 列表中的每一个字典,相当于一行
f = pd.DataFrame(d, index=['a', 'b'])
print(f)

# 结果:
   one  three  two
a    1    NaN    2
b   11   13.0   12
(5)方法五:由字典组成的字典
data = {
    'name':{'a':'Jack', 'b': 'Mary'},
    'sex':{'a': 18, 'b':19}
}     # 相当于指定行标签
f = pd.DataFrame(data)
print(f)

# 结果:
   name  sex
a  Jack   18
b  Mary   19
(6)小结
# 1.
# 用字典的形式建立DataFrame,其column不能更改为你指定的值,只能更改已有列的顺序。
# 而用二维数组直接建立的可以用column更改默认的数字列标签。
# 可以这样理解,因为以字典的形式建立DataFrame其列名已经建立,就是字典的key,所以再用column只能更改顺序;用二维数组没有建立列名,是默认的数字标签,所以能改
# 2.
# 用字典Series形式建立DataFrame其column的值可以与列数不相同,其他的建立DataFrame其column的值与列数必须相同
# 3.
# 由数组/list组成的字典,由Series组成的字典,由字典组成的列表是指定了列名
# 由二维数组建立是行列名都为设置,是数字标签
# 由字典组成的字典是行列名都已经指定

二、Pandas数据结构Dataframe:索引

这个模块的主要知识有:选择列 / 选择行 / 切片 / 布尔判断

1.选择行与列
df = pd.DataFrame(np.random.rand(12).reshape(3,4)*100,
                   index = ['one','two','three'],
                   columns = ['a','b','c','d'])
print(df)
print('列----')
# 按照列名选择列,只选择一列输出Series,选择多列输出Dataframe 
print(df.a)  # 也可以用print(df['a']),但是我个人建议如果是选择该列用前者,添加列用后者
print(df[['a', 'c']]) # 也可以用df.loc[:, ['a', 'c']]
print('-----')
print(df[:1])  # df[]中为数字时,默认选择行,且只能进行切片的选择,不能单独选择(df[0])
# df[]默认选择列,[]中写列名(所以一般数据colunms都会单独制定,不会用默认数字列名,以免和index冲突)
print('行------')

# 按照index选择行,只选择一行输出Series,选择多行输出Dataframe
print(df.loc['one'])  # 不能用df['one']  df[]默认索引的是列
print(df.loc[['one', 'three']])

# 结果:
               a          b          c          d
one    11.744031  71.783455  54.043797  74.911762
two    25.748061  18.386051  23.297262  26.125503
three  98.138206  58.591411  57.216109  74.354878
列----
one      11.744031
two      25.748061
three    98.138206
Name: a, dtype: float64
               a          c
one    11.744031  54.043797
two    25.748061  23.297262
three  98.138206  57.216109
-----
             a          b          c          d
one  11.744031  71.783455  54.043797  74.911762
行------
a    11.744031
b    71.783455
c    54.043797
d    74.911762
Name: one, dtype: float64
               a          b          c          d
one    11.744031  71.783455  54.043797  74.911762
three  98.138206  58.591411  57.216109  74.354878

小结:

  1. df['列名']一般用于选择列
  2. df.loc[‘行名’]用于选择行
  3. df.loc['行名', '列名']来选择某一行某一列
  4. df[数字]中传入数字时,默认选择行,且只能进行切片的选择 【eg:df[:5],不能单独选择df[0](对行切片一般不使用该方法,该方法基本上不用)】

2.df.iloc[] 数字选择行
# df.iloc[] - 按照整数位置(从轴的0到length-1)选择行
# 类似list的索引,其顺序就是dataframe的整数位置,从0开始计

df = pd.DataFrame(np.arange(16).reshape(4, 4),
                 index=['one', 'two', 'three', 'four'],
                 columns=['a', 'b', 'c', 'd'])  # columns 记得加s
print(df)
# 单位置索引
print(df.iloc[0])
# 多位置索引
print(df.iloc[[2, 0]])
# 切片
print('切片----')
print(df.iloc[:-1])  # 末端不包含

# 结果:
        a   b   c   d
one     0   1   2   3
two     4   5   6   7
three   8   9  10  11
four   12  13  14  15
a    0
b    1
c    2
d    3
Name: one, dtype: int32
       a  b   c   d
three  8  9  10  11
one    0  1   2   3
切片----
       a  b   c   d
one    0  1   2   3
two    4  5   6   7
three  8  9  10  11

小结:

  1. df.iloc[0],表示选择第一行
  2. df.iloc[1:3],切片,表示选择第二行与第三行。
3.数据子集的获取

(1)df.loc[]      []      左闭右闭      行标签/列标签
(2)df.iloc[]      [)      左闭右开      数字索引
(3)df.ix[]         具有上面的两种功能:数字索引、行/列标签     数字是[) 行/列标签是[]

df = pd.DataFrame(np.random.rand(12).reshape(3,4)*100,
                   index = ['one','two','three'],
                   columns = ['a','b','c','d'])
print(df)
print(df.loc[:, ['a', 'c']])
print(df.iloc[0:2, 1:3])
print(df.ix[0:2, ['a', 'c']])

# 结果:
               a          b          c          d
one    63.666351  61.163233  31.822639  78.653631
two    49.693777  52.420641  42.267130  53.031000
three  44.693220  16.741017  11.834082  97.288596
               a          c
one    63.666351  31.822639
two    49.693777  42.267130
three  44.693220  11.834082
             b          c
one  61.163233  31.822639
two  52.420641  42.267130
             a          c
one  63.666351  31.822639
two  49.693777  42.267130

4.布尔型索引

(1)布尔类型的行列共用

# 和Series原理相同
df = pd.DataFrame(np.random.rand(16).reshape(4,4)*100,
                   index = ['one','two','three','four'],
                   columns = ['a','b','c','d'])
print(df)
print('------')
print(df>50)
print('------')
print(df[df>50])
# 行列的布尔类型类似,用df['one']  df.loc['a']等等

# 结果:
               a          b          c          d
one    17.212809  74.314714  10.156837  72.622754
two    88.294727  48.804259  31.103894  20.837973
three  95.101094  34.875227  78.032575  93.951124
four   94.727082  43.795659  86.518682  90.068478
------
           a      b      c      d
one    False   True  False   True
two     True  False  False  False
three   True  False   True   True
four    True  False   True   True
------
               a          b          c          d
one          NaN  74.314714        NaN  72.622754
two    88.294727        NaN        NaN        NaN
three  95.101094        NaN  78.032575  93.951124
four   94.727082        NaN  86.518682  90.068478

(2)布尔类型的行与列

df = pd.DataFrame({
    'key1':np.arange(5),
    'key2':np.arange(5, 10),
}, index=list('abcde'))
print(df)
print('------')
s = pd.Series({'a':True, 'b':False, 'c':True, 'd':False, 'e':False})
print(df[s])

s2 = pd.Series({'key1':True, 'key2':False})
print(s2)
print(df.columns[s2])

# 结果:
   key1  key2
a     0     5
b     1     6
c     2     7
d     3     8
e     4     9
------
   key1  key2
a     0     5
c     2     7
key1     True
key2    False
dtype: bool
Index(['key1'], dtype='object')

5.多重索引
# 多重索引:比如同时索引行和列
# 先选择列再选择行 —— 相当于对于一个数据,先筛选字段,再选择数据量
df = pd.DataFrame(np.random.rand(16).reshape(4,4)*100,
                   index = ['one','two','three','four'],
                   columns = ['a','b','c','d'])
print(df)
print('------')

print(df['a'].loc[['one','three']])   # 选择a列的one,three行

# 结果:
               a          b          c          d
one    73.315488  34.853760  22.059922  44.274220
two     7.484602  22.595569  32.362358  26.621247
three  21.273322  16.585421  48.346943  49.811086
four   79.518511   4.416195  29.054869  76.588620
------
one      73.315488
three    21.273322
Name: a, dtype: float64

三、Pandas数据结构Dataframe:基本技巧

这个模块的主要知识点有:数据查看、转置 / 添加、修改、删除值 / 对齐 / 排序

1.数据查看、转置
df = pd.DataFrame(np.random.rand(5, 2),
                 columns=['a', 'b'])
print(df)
print(df.head(2))  # .head()查看头部数据,不带参数默认是5行
print(df.tail(2))  # .tail()查看尾部数据,不带参数默认是5行

# 转置
print(df.T)

# 结果:
          a         b
0  0.178140  0.626120
1  0.875550  0.106871
2  0.051926  0.959511
3  0.770076  0.005052
4  0.846975  0.292112
         a         b
0  0.17814  0.626120
1  0.87555  0.106871
          a         b
3  0.770076  0.005052
4  0.846975  0.292112
         0         1         2         3         4
a  0.17814  0.875550  0.051926  0.770076  0.846975
b  0.62612  0.106871  0.959511  0.005052  0.292112
2.添加与修改
# 用df[]修改列   df.loc[]修改行  df[].loc[]修改某一元素值
df = pd.DataFrame(np.arange(20).reshape(4, 5),
                 columns=list('abcde'))
print(df)

# 修改元素值
df['a'].loc[0] = 100
print(df)

# 添加元素值
print('添加-------')
df['f'] = 300
print(df)

# 结果:
    a   b   c   d   e
0   0   1   2   3   4
1   5   6   7   8   9
2  10  11  12  13  14
3  15  16  17  18  19
     a   b   c   d   e
0  100   1   2   3   4
1    5   6   7   8   9
2   10  11  12  13  14
3   15  16  17  18  19
添加-------
     a   b   c   d   e    f
0  100   1   2   3   4  300
1    5   6   7   8   9  300
2   10  11  12  13  14  300
3   15  16  17  18  19  300
3.删除 del / drop() del语句 删除列 drop()删除行/列
f = pd.DataFrame(np.arange(20).reshape(4, 5),
                 columns=list('abcde'))
print(df)

# del语句 - 删除列
del df['a']  # 使用del删除列,会删除df本身的数据,而是生成新的DataFrame
print(df)

# drop()语句删除列
print(df.drop(['e'], axis=1))  # drop()删除列,需要加上axis = 1,inplace=False → 删除后生成新的数据,不改变原数据
# drop()删除行,inplace=False → 删除后生成新的数据,不改变原数据
print('删除行-----')
print(df.drop(0))
print(df.drop(1))  # 可以看到,使用drop()方法删除行/列都不是删除df本身的数据,而是生成新的DataFrame

# 结果:
    a   b   c   d   e
0   0   1   2   3   4
1   5   6   7   8   9
2  10  11  12  13  14
3  15  16  17  18  19
    b   c   d   e
0   1   2   3   4
1   6   7   8   9
2  11  12  13  14
3  16  17  18  19
    b   c   d
0   1   2   3
1   6   7   8
2  11  12  13
3  16  17  18
删除行-----
    b   c   d   e
1   6   7   8   9
2  11  12  13  14
3  16  17  18  19
    b   c   d   e
0   1   2   3   4
2  11  12  13  14
3  16  17  18  19

小结:
1.del和drop([], axis=1)用来删除列,drop()用来删除行
2.del会删除df本身的数据,而使用drop()方法删除行/列都不是删除df本身的数据,而是生成新的DataFrame

4.对齐
df1 = pd.DataFrame(np.random.randn(10, 4), columns=['A', 'B', 'C', 'D'])
df2 = pd.DataFrame(np.random.randn(7, 3), columns=['A', 'B', 'C'])
print(df1 + df2)
# DataFrame对象之间的数据自动按照列和索引(行标签)对齐

# 结果:
          A         B         C   D
0 -0.286501  0.101564  0.934023 NaN
1  0.002405 -0.674116 -1.688925 NaN
2 -1.374691  0.188597  0.161464 NaN
3 -1.209863 -1.844409 -0.591461 NaN
4 -2.605153 -1.473555  1.891570 NaN
5  2.782283  1.193310 -1.139518 NaN
6  1.494297  1.553604  3.075171 NaN
7       NaN       NaN       NaN NaN
8       NaN       NaN       NaN NaN
9       NaN       NaN       NaN NaN
5.排序1 – 按值排序 .sort_values
# 同样适用于Series
df = pd.DataFrame(np.random.rand(4,4)*100,
                 columns=['a', 'b', 'c', 'd'])
print(df)
# 单列排序
print(df.sort_values(['a'], ascending=False)) # ascending参数:设置升序降序,默认升序
print('多列排序------')
# 多列排序,按列顺序排序
print(df.sort_values(['a', 'd'])) # 先按a排序,如果a的值相同,则按d的值排序

# 结果:
           a          b          c          d
0  36.300085  90.999611  87.883077  39.251081
1  16.769310  99.653961  66.176705  10.763438
2  69.271539  94.620625  16.709941  95.833152
3  31.870412  92.897303  45.783337  43.051783
           a          b          c          d
2  69.271539  94.620625  16.709941  95.833152
0  36.300085  90.999611  87.883077  39.251081
3  31.870412  92.897303  45.783337  43.051783
1  16.769310  99.653961  66.176705  10.763438
多列排序------
           a          b          c          d
1  16.769310  99.653961  66.176705  10.763438
3  31.870412  92.897303  45.783337  43.051783
0  36.300085  90.999611  87.883077  39.251081
2  69.271539  94.620625  16.709941  95.833152
6.排序2 – 索引排序 .sort_index
# 与.sort_values类似
df1 = pd.DataFrame(np.random.rand(16).reshape(4,4)*100,
                  index = [5,4,3,2],
                   columns = ['a','b','c','d'])
df2 = pd.DataFrame(np.random.rand(16).reshape(4,4)*100,
                  index = ['h','s','x','g'],
                   columns = ['a','b','c','d'])
# 按照index排序
# 默认 ascending=True, inplace=False
print(df1)
print(df1.sort_index())
print(df2)
print(df2.sort_index())

# 结果:
           a          b          c          d
5  10.912363  66.069285  75.108926  50.976926
4  10.068745  89.445559  68.636782  56.758989
3   5.706953  17.755349  10.428633  31.123841
2  87.497426  76.308941  85.110218  97.168951
           a          b          c          d
2  87.497426  76.308941  85.110218  97.168951
3   5.706953  17.755349  10.428633  31.123841
4  10.068745  89.445559  68.636782  56.758989
5  10.912363  66.069285  75.108926  50.976926
           a          b          c          d
h  70.385483  10.462891  83.496788  82.744301
s  12.271862  25.484720  18.975885  25.769192
x  83.282964  58.578331   5.013539  12.543449
g  62.352057  18.190354  71.342096  28.424552
           a          b          c          d
g  62.352057  18.190354  71.342096  28.424552
h  70.385483  10.462891  83.496788  82.744301
s  12.271862  25.484720  18.975885  25.769192
x  83.282964  58.578331   5.013539  12.543449

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/84775.html

(0)
小半的头像小半

相关推荐

极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!