首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >[编程经验] Pandas入门(一)

[编程经验] Pandas入门(一)

作者头像
用户1622570
发布2018-04-11 16:06:34
6990
发布2018-04-11 16:06:34
举报

今天和大家介绍一个非常厉害的数据处理的工具,Pandas。Python中比较有名的数据处理的库除了Pandas,还有Numpy,Matplotlib。这三个在平时学习的时候的会经常遇到,而且每一个功能都非常强大。对于这类库的学习,开始的时候,总是遇到某个问题的时候,就会去找度娘,所以有必要总结一下,方便自己也方便大家。恩,废话不多说,下面开始。

Pandas主要包括两种数据结构,一个是Series,一个是DataFrame。可以理解为多个Series组合在一起就构成了DataFrame。下面我分别介绍一下,主要有如何创建一个Series或者DataFrame,以及他们对应的常用的方法。

# Series

创建一个Series的主要方法是pd.Series(),可以看到,一个Series可以包含字符串,整型,列表,元组,甚至是字典。

# - * - coding:utf-8 - * -
import pandas as pd
import numpy as np

h = ('字符串', 100, [1, 2, 3], (1, 2, 3), {"1": 1})
s = pd.Series(h)
print type(s)
print s
"""
<class 'pandas.core.series.Series'>
0          字符串
1          100
2    [1, 2, 3]
3    (1, 2, 3)
4    {u'1': 1}
dtype: object
"""

然后可以通过位置参数,对Series进行切片,比如

print s[0:2]
"""
0    字符串
1    100
"""

然后可以通过index参数,给Series加上索引值;

f = pd.Series(h, index=['first', 'second', 'third',
                        
                         'four', 'five'])
print f
"""
first           字符串
second          100
third     [1, 2, 3]
four      (1, 2, 3)
five      {u'1': 1}
"""

有了索引值之后,就可以通过索引值进行切片;

print f['first': 'second']
"""
first     字符串
second    100
"""
print f['second']
"""
100
"""

但是如果想查看不连续的值,怎么选择呢?

print f[['first', 'third', 'five']]
"""
first          字符串
third    [1, 2, 3]
five     {u'1': 1}
"""

注意这里多了一层中括号。

# DataFrame

DataFrame也叫数据框,数据框是一种非常高效的数据结构,Pandas的数据框和R语言的数据框差不多的道理,具体操作有所区别。数据框中也可以包含各种数据类型,比如字符型,整型等。首先是创建一个DataFrame, index参数是添加索引值,注意index类似于Excel里面的行号,是第一个维度。

import pandas as pd
import numpy as np

sample_da = np.array(np.random.standard_normal(24), 
               dtype=np.float32).reshape((4, 6))
sample_da_pd = pd.DataFrame(sample_da,
                  index=['A', 'B', 'C', 'D'])
print type(sample_da_pd)
print sample_da_pd
"""
<class 'pandas.core.frame.DataFrame'>
          0         1         2         3         4         5
A  0.381265  1.674450 -0.718045 -1.558043  0.831959  0.249016
B  1.432158 -1.234497 -1.854317  1.661535  0.873308 -0.309029
C -1.320369  0.163068 -0.282765 -1.631093 -0.428650 -0.795699
D -1.715232  1.276944  0.530508  1.687833  2.490440 -0.475695
"""

DataFrame也可以添加列名,参数是columns;

sample_da_pd = pd.DataFrame(sample_da,
         columns=['A', 'B', 'C', 'D','E','F'])
print sample_da_pd
"""
          A         B         C         D         E         F
0 -0.730475 -1.818166 -0.316464 -0.825278  0.606036  0.028023
1 -0.947185  0.649167 -0.920713  2.749960 -0.450231  1.752944
2 -0.294413 -0.700613  0.281514  0.276904 -1.488047 -1.876655
3  1.265560 -1.521396 -0.292039 -0.682685  0.214682 -2.375128
"""

如果想给DataFrame新添加一列,可以这样,后面显示不全的话,自己可以动手做一下。。

sample_da_pd['new_columns'] = range(10, 14)
print sample_da_pd
"""
 A         B         C         D         E         F  new_columns
1  1.882097 -0.322483  0.395698 -1.408993 -1.038652 -0.201654           10
2 -0.815007  0.718386 -0.928622  0.444755  0.772454  1.316488           11
3  0.179675 -0.311279  0.652153 -0.865288  1.270869  1.632239           12
4 -1.527354 -1.047910  0.102873 -0.783220  0.153513 -0.635148           13
"""

如果想查看某一行全部的数据,可以使用 ix方法

row1 = sample_da_pd.ix['1']
row2 = sample_da_pd.ix['2']
print row1
"""
A               0.848085
B               0.423423
C              -0.556165
D               0.832503
E              -0.360387
F              -0.484729
"""
print row2
"""
A               2.686568
B              -2.187451
C               0.397000
D              -0.192859
E              -0.251258
F              -0.718637
"""

然后如果想查看某一列的数据呢,.ix的第一个参数表示行索引,第二个参数表示列索引。

col1 = sample_da_pd.ix[:, 'A']
print col1

"""
1   -0.046429
2   -0.137252
3   -0.144563
4   -0.123651
"""
# 查看具体某个位置的值
A3 = sample_da_pd.ix[3, 'A']
print A3
"""
-0.123651
"""
F2 = sample_da_pd.ix[2, 'F']
print F2
"""
-0.0608439
"""

# Pandas 文件操作

首先我们看一下,怎么将一个DataFrame对象保存到csv文件,以及如何读取。

import pandas as pd
import numpy as np

sample_da = np.array(np.random.standard_normal(24),
              dtype=np.float32).reshape((4, 6))
sample_da_pd = pd.DataFrame(sample_da, 
                        index=['1', '2', '3', '4'],
                columns=['A', 'B', 'C', 'D', 'E', 'F'])

sample_da_pd.to_csv("sample_1.csv", index=None)
sample_da_pd = pd.read_csv("sample_1.csv")
print sample_da_pd.index
print type(sample_da_pd)
"""
RangeIndex(start=0, stop=4, step=1)
<class 'pandas.core.frame.DataFrame'>
"""

这里举一个csv文件的栗子,pandas还支持Excel,hdf,json,以及二进制等多种文件格式,有需要的时候,可以去尝试一下。保存不同文件类型的一个最主要的问题就是占用的硬盘大小不一样,如果要处理大量数据,这个问题就值得考虑。

可以使用head, tail 函数查看数据前几行,或者后几行, 默认是5.

import pandas as pd
sample_da_pd = pd.read_csv("sample_1.csv")

print sample_da_pd.head(3)
print
print sample_da_pd.tail(4)
"""
          A         B         C         D         E         F
0 -0.129107 -1.265953  1.063227 -0.155013 -1.957152 -1.014818
1  0.053083 -0.542291  0.263785  0.569444 -1.205508 -0.640574
2  0.749401  0.233683 -0.314593  0.405725 -1.037105 -1.653296

          A         B         C         D         E         F
0 -0.129107 -1.265953  1.063227 -0.155013 -1.957152 -1.014818
1  0.053083 -0.542291  0.263785  0.569444 -1.205508 -0.640574
2  0.749401  0.233683 -0.314593  0.405725 -1.037105 -1.653296
3  0.655921 -0.372295 -0.571558  0.363412 -0.656897 -0.356786
"""

索引,注意这里对于DataFrame的某一列或者行来说,它的数据类型是Series。

s_A = sample_da_pd['A']
print type(s_A)
print s_A
"""
<class 'pandas.core.series.Series'>
0   -0.129107
1    0.053083
2    0.749401
3    0.655921
"""

values方法可以将DataFrame转化为Numpy数组。

DataFrame2numpy = sample_da_pd.values
print type(DataFrame2numpy)
"""
<type 'numpy.ndarray'>
"""

# loc, iloc

import pandas as pd
sample_da_pd = pd.read_csv("sample_1.csv")
print sample_da_pd.head(3)
"""
          A         B         C         D         E         F
0 -0.129107 -1.265953  1.063227 -0.155013 -1.957152 -1.014818
1  0.053083 -0.542291  0.263785  0.569444 -1.205508 -0.640574
2  0.749401  0.233683 -0.314593  0.405725 -1.037105 -1.653296
"""
print sample_da_pd[0:3]
"""
          A         B         C         D         E         F
0 -0.129107 -1.265953  1.063227 -0.155013 -1.957152 -1.014818
1  0.053083 -0.542291  0.263785  0.569444 -1.205508 -0.640574
2  0.749401  0.233683 -0.314593  0.405725 -1.037105 -1.653296
"""
print sample_da_pd["A"]
"""
0   -0.129107
1    0.053083
2    0.749401
3    0.655921
"""
print sample_da_pd.loc[:, ['A', 'B']]
"""
          A         B
0 -0.129107 -1.265953
1  0.053083 -0.542291
2  0.749401  0.233683
3  0.655921 -0.372295
"""

print sample_da_pd.loc[0, ['A', 'B']]
"""
A   -0.129107
B   -1.265953
"""
print sample_da_pd.loc[0:2, ['A', 'B']]
"""
          A         B
0 -0.129107 -1.265953
1  0.053083 -0.542291
2  0.749401  0.233683
"""

print sample_da_pd.iloc[0:2, 0:2]
"""
          A         B
0 -0.129107 -1.265953
1  0.053083 -0.542291
"""
print sample_da_pd.iloc[0, 0:2]
"""
A   -0.129107
B   -1.265953
"""
print sample_da_pd.iloc[0, 0]
"""
-0.129107072949
"""

今天先介绍到这里,主要介绍了Pandas的基本操作。下次会再介绍一下Pandas的基本数据统计,分组,时间序列等相关知识。欢迎大家关注!

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2017-06-16,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 机器学习和数学 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档