pandas小记:pandas数据结构

版权声明:本文为博主皮皮http://blog.csdn.net/pipisorry原创文章,未经博主允许不得转载。 https://blog.csdn.net/pipisorry/article/details/18010307

http://blog.csdn.net/pipisorry/article/details/18010307

pandas的数据 结构:Series、DataFrame、索引对象
pandas基本功能:重新索引,丢弃指定轴上的项,索引、选取和过滤,算术运算和数据对齐,函数应用和映射,排序和排名,带有重复值的轴索引

Pandas介绍

pandas含有使数据分析工作变得更快更简单的高级数据结构和操作工具。它是基于NumPy构建的,让以NumPy为中心的应用变得更加简单。

通常建议你先学习NumPy,一个支持多维数组的库。但因为NumPy越来越成为一个被其他库所使用核心库,这些库通常具有更优雅的接口。使用NumPy(或者笨重的Matlab)达到同样的目的会很麻烦。

pandas可以以各种格式(包括数据库)输入输出数据、执行join以及其他SQL类似的功能来重塑数据、熟练地处理缺失值、支持时间序列、拥有基本绘图功能和统计功能,等等还有很多。

pandas常量

pandas空值的表示(None, np.NaN, np.NaT, pd.NaT)

NaN: not a number, NaN is the default missing value marker forreasons of computational speed and convenience, we need to be able to easilydetect this value with data of different types: floating point, integer,boolean, and general object.

None: treats None like np.nan. In many cases, however, the Python None will arise and we wish to also consider that “missing” or “null”.

NaT:  Datetimes, For datetime64[ns] types, NaT represents missing values. This is a pseudo-native sentinel value that can be represented by numpy in a singular dtype (datetime64[ns]). pandas objects provide intercompatibility between NaT and NaN.

inf: Prior to version v0.10.0 inf and -inf were also considered to be “null” in computations. This is no longer the case by default; use the mode.use_inf_as_null option to recover it.

Note: 缺失值的判断要用np.isnan(),而不能使用a[0] == np.NaN.[numpy教程:逻辑函数Logic functions ]

[Working with missing data]

Pandas数据结构

与Numpy一样,用dtype属性来显示数据类型,Pandas主要有以下几种dtype:

  • object -- 代表了字符串类型
  • int -- 代表了整型
  • float -- 代表了浮点数类型
  • datetime -- 代表了时间类型
  • bool -- 代表了布尔类型

pandas安装

pip install pandas

好像如果使用pd.read_excel要安装xlrd:pip install xlrd

引入相关包

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

皮皮blog

pandas数据结构

pandas中的主要数据对象是Series和DataFrame。虽然它们不是没一个问题的通用解决方案,但提供了一个坚实的,易于使用的大多数应用程序的基础。

Series

Series是一个一维的类似的数组对象,包含一个数组的数据(任何NumPy的数据类型)和一个与数组关联的数据标签,被叫做索引 。Seriers的交互式显示的字符串表示形式是索引在左边,值在右边。

lz通过使用series自带的函数,发现它和python dict类型太像了,基本一样!就如下所述:Series是一个定长的,有序的字典,因为它把索引和值映射起来了。它可以适用于许多需要一个字典的函数。

总结说就是,他像一个数组,你可以像数组那样索引,他也想一个字典,你可以像字典那样索引。

series对象创建

如果不给数据指定索引,一个包含整数0到 N-1 (这里N是数据的长度)的默认索引被创建。 你可以分别的通过它的values 和index 属性来获取Series的数组表示和索引对象:

最简单的Series是由一个数组的数据构成:

In [4]: obj = Series([4, 7, -5, 3])
In [5]: obj
Out[5]:
0 4
1 7
2 -5
3 3
In [6]: obj.values
Out[6]: array([ 4, 7, -5, 3])
In [7]: obj.index
Out[7]: Int64Index([0, 1, 2, 3])

通常,需要创建一个带有索引来确定每一个数据点的Series:

In [8]: obj2 = Series([4, 7, -5, 3], index=['d', 'b', 'a', 'c'])
In [9]: obj2
Out[9]:
d 4
b 7
a -5
c 3

Note: pandas对象(series和dataframe)的index是可以修改的

df.index = range(len(df))重新将index的值修改成了从0开始。这也许是和dict的一个不同吧。

[Start index at 1 when writing Pandas DataFrame to CSV]

另一种思考的方式是,Series是一个定长的,有序的字典,因为它把索引和值映射起来了。它可以适用于许多需要一个字典的函数:

In [18]: 'b' in obj2
Out[18]: True
In [19]: 'e' in obj2
Out[19]: False

如果你有一些数据在一个Python字典中,你可以通过传递字典来从这些数据创建一个Series

In [20]: sdata = {'Ohio': 35000, 'Texas': 71000, 'Oregon': 16000, 'Utah': 5000}
In [21]: obj3 = Series(sdata)

只传递一个字典的时候,结果Series中的索引将是排序后的字典的建。

In [23]: states = [‘California’, ‘Ohio’, ‘Oregon’, ‘Texas’]
In [24]: obj4 = Series(sdata, index=states)

In [25]: obj4

Out[25]:California NaNOhio 35000Oregon 16000Texas 71000

在这种情况下, sdata 中的3个值被放在了合适的位置,但因为没有发现对应于 ‘California’ 的值,就出现了NaN (不是一个数),这在pandas中被用来标记数据缺失或NA 值。我使用“missing”或“NA”来表示数度丢失。

Series的字典也以嵌套的字典的字典格式的方式来处理:

In [62]: pdata = {'Ohio': frame3['Ohio'][:-1],
  ....: 'Nevada': frame3['Nevada'][:2]}

In [63]: DataFrame(pdata)
Out[63]:
     Nevada Ohio
2000    NaN  1.5
2001    2.4  1.7

series对象转换为字典dict

从series的字典构建中可以看出他们互相转换的机制了:将series对象的index作为keys,对应的值作为dict的value。

obj2 = pd.Series([4, 7, -5, 3], index=['d', 'b', 'a', 'c'])
d    4
b    7
a   -5
c    3
dtype: int64
In[27]: dict(obj2)
{'a': -5, 'b': 7, 'c': 3, 'd': 4}

series对象转换为tuple列表

list(se.items())

pandas中用函数isnull 和notnull 来检测数据丢失

In [26]: pd.isnull(obj4) In [27]: pd.notnull(obj4)
Out[26]:                 Out[27]:
California True          California False
Ohio False               Ohio True
Oregon False             Oregon True
Texas False              Texas True

Series也提供了这些函数的实例方法:

In [28]: obj4.isnull()
Out[28]:
California True
Ohio False
Oregon False
Texas False

series对象操作

series对象迭代

Series.iteritems()

Lazily iterate over (index, value) tuples

[i.split(',') for _, i in df['VenueCategory'].iteritems()]

与正规的NumPy数组相比,你可以使用索引里的值来选择一个单一值或一个值集:

In [11]: obj2['a']
Out[11]: -5
In [12]: obj2['d'] = 6
In [13]: obj2[['c', 'a', 'd']]
Out[13]:
c 3
a -5
d 6

NumPy数组操作,例如通过一个布尔数组过滤,纯量乘法,使用数学函数,将会保持索引和值间的关联:

In [14]: obj2
Out[14]:
d 6
b 7
a -5
c 3
In [15]: obj2[obj2 > 0]   In [16]: obj2 * 2       In [17]: np.exp(obj2)
Out[15]:                  Out[16]:                Out[17]:
d 6                       d 12                    d 403.428793
b 7                       b 14                    b 1096.633158
c 3                       a -10                   a 0.006738
                          c 6                     c 20.085537

在许多应用中Series的一个重要功能是在算术运算中它会自动对齐不同索引的数据:

In [29]: obj3        In [30]: obj4
Out[29]:             Out[30]:
Ohio 35000           California NaN
Oregon 16000         Ohio 35000
Texas 71000          Oregon 16000
Utah 5000            Texas 71000
In [31]: obj3 + obj4
Out[31]:
California NaN
Ohio 70000
Oregon 32000
Texas 142000
Utah NaN

Series对象本身和它的索引都有一个 name 属性,它和pandas的其它一些关键功能整合在一起:

In [32]: obj4.name = 'population'
In [33]: obj4.index.name = 'state'
In [34]: obj4
Out[34]:
state
California NaN
Ohio 35000
Oregon 16000
Texas 71000
Name: population

Series索引更改

可以通过赋值就地更改:

In [35]: obj.index = ['Bob', 'Steve', 'Jeff', 'Ryan']
In [36]: obj
Out[36]:
Bob 4
Steve 7
Jeff -5
Ryan 3

series值替换

ser.replace(1, 11)

可以使用字典映射:将1替换为11,将2替换为12
ser.replace({1:11, 2:12})

series列分割转换成dataframe

s = pd.Series(['15,15', '17,17', '36,36', '24,24', '29,29'])
print(type(s))
print(s)
s = s.apply(lambda x: pd.Series(x.split(',')))
print(type(s))
print(s)

<class 'pandas.core.series.Series'>
0    15,15
1    17,17
2    36,36
3    24,24
4    29,29
dtype: object
<class 'pandas.core.frame.DataFrame'>
    0   1
0  15  15
1  17  17
2  36  36
3  24  24
4  29  29

Note: series对象直接应用apply方法是不会改变原series对象的,要赋值修改。

[series属性和方法参考pandas.Series]

皮皮blog

DataFrame

一个Datarame表示一个表格,类似电子表格的数据结构,包含一个经过排序的列表集,它们没一个都可以有不同的类型值(数字,字符串,布尔等等)。Datarame有行和列的索引;它可以被看作是一个Series的字典(每个Series共享一个索引)。与其它你以前使用过的(如Rdata.frame )类似Datarame的结构相比,在DataFrame里的面向行和面向列的操作大致是对称的。在底层,数据是作为一个或多个二维数组存储的,而不是列表,字典,或其它一维的数组集合。

因为DataFrame在内部把数据存储为一个二维数组的格式,因此你可以采用分层索引以表格格式来表示高维的数据。分层索引是pandas中许多更先进的数据处理功能的关键因素。

构建DataFrame

可能的传递到DataFrame的构造器
二维ndarray 一个数据矩阵,有可选的行标和列标
数组,列表或元组的字典 每一个序列成为DataFrame中的一列。所有的序列必须有相同的长度。
NumPy的结构/记录数组 和“数组字典”一样处理
Series的字典 每一个值成为一列。如果没有明显的传递索引,将结合每一个Series的索引来形成结果的行索引。
字典的字典 每一个内部的字典成为一列。和“Series的字典”一样,结合键值来形成行索引。
字典或Series的列表 每一项成为DataFrame中的一列。结合字典键或Series索引形成DataFrame的列标。
列表或元组的列表 和“二维ndarray”一样处理
另一个DataFrame DataFrame的索引将被使用,除非传递另外一个
NumPy伪装数组(MaskedArray) 除了蒙蔽值在DataFrame中成为NA/丢失数据之外,其它的和“二维ndarray”一样

字典或NumPy数组

最常用的一个是用一个相等长度列表的字典或NumPy数组:

data = {'state': ['Ohio', 'Ohio', 'Ohio', 'Nevada', 'Nevada'],
        'year': [2000, 2001, 2002, 2001, 2002],
        'pop': [1.5, 1.7, 3.6, 2.4, 2.9]}
frame = DataFrame(data)

由此产生的DataFrame和Series一样,它的索引会自动分配,并且对列进行了排序:

In [38]: frame
Out[38]:
  pop    state year
0 1.5     Ohio 2000
1 1.7     Ohio 2001
2 3.6     Ohio 2002
3 2.4   Nevada 2001
4 2.9   Nevada 2002

如果你设定了一个列的顺序,DataFrame的列将会精确的按照你所传递的顺序排列:

DataFrame(data, columns=['year', 'state', 'pop'])

和Series一样,如果你传递了一个行,但不包括在 data 中,在结果中它会表示为NA值:

In [40]: frame2 = DataFrame(data, columns=['year', 'state', 'pop', 'debt'],
   ....: index=['one', 'two', 'three', 'four', 'five'])
In [41]: frame2
Out[41]:
       year state   pop debt
one    2000 Ohio    1.5  NaN
two    2001 Ohio    1.7  NaN
three  2002 Ohio    3.6  NaN
four   2001 Nevada  2.4  NaN
five   2002 Nevada  2.9  NaN

Creating a DataFrame by passing a numpy array, with a datetime indexand labeled columns:

In [6]: dates = pd.date_range('20130101', periods=6)

In [7]: dates
Out[7]: 
DatetimeIndex(['2013-01-01', '2013-01-02', '2013-01-03', '2013-01-04',
               '2013-01-05', '2013-01-06'],
              dtype='datetime64[ns]', freq='D')

In [8]: df = pd.DataFrame(np.random.randn(6,4), index=dates, columns=list('ABCD'))

In [9]: df
Out[9]: 
                   A         B         C         D
2013-01-01  0.469112 -0.282863 -1.509059 -1.135632
2013-01-02  1.212112 -0.173215  0.119209 -1.044236
2013-01-03 -0.861849 -2.104569 -0.494929  1.071804
2013-01-04  0.721555 -0.706771 -1.039575  0.271860
2013-01-05 -0.424972  0.567020  0.276232 -1.087401
2013-01-06 -0.673690  0.113648 -1.478427  0.524988

嵌套的字典的字典格式

In [57]: pop = {'Nevada': {2001: 2.4, 2002: 2.9},
   ....: 'Ohio': {2000: 1.5, 2001: 1.7, 2002: 3.6}}

如果被传递到DataFrame,它的外部键会被解释为列索引,内部键会被解释为行索引:

In [58]: frame3 = DataFrame(pop)
In [59]: frame3
     Nevada Ohio
2000    NaN  1.5
2001    2.4  1.7
2002    2.9  3.6

当然,你总是可以对结果转置:

In [60]: frame3.T
2000 2001 2002
Nevada NaN 2.4 2.9
Ohio 1.5 1.7 3.6

内部字典的键被结合并排序来形成结果的索引。如果指定了一个特定的索引,就不是这样的了:

In [61]: DataFrame(pop, index=[2001, 2002, 2003])
        Nevada Ohio
  2001     2.4  1.7
  2002     2.9  3.6
  2003     NaN  NaN

通过series对象创建

df.median()就是一个series对象

pd.DataFrame([df.median(), df.mean(), df.std()], index=['median', 'mean', 'std'])

dataframe数据转换成其它格式

dataframe转换为字典

简单可知从字典构建dataframe就知道dataframe是如何转换为字典的了,dataframe会转换成嵌套dict。

如果只是选择一列进行转换,就相当于是将series对象转换成dict。

data = {'state': ['Ohio', 'Ohio', 'Ohio', 'Nevada', 'Nevada'], 'year': [2000, 2001, 2002, 2001, 2002],  'pop': [1.5, 1.7, 3.6, 2.4, 2.9]}
frame = pd.DataFrame(data, index = [2,3,4,5, 6])
   pop   state  year
2  1.5    Ohio  2000
3  1.7    Ohio  2001
4  3.6    Ohio  2002
5  2.4  Nevada  2001
6  2.9  Nevada  2002
In[23]: dict(frame['year'])
{2: 2000, 3: 2001, 4: 2002, 5: 2001, 6: 2002}
In[24]: dict(frame[['pop', 'year']])
{'pop': 2    1.5
 3    1.7
 4    3.6
 5    2.4
 6    2.9
 Name: pop, dtype: float64,

'year': 2    2000
 3    2001
 4    2002
 5    2001
 6    2002
 Name: year, dtype: int64}
Note: 上面是一个嵌套dict,通过dict['pop'][2]可以得到1.5。

dataframe转换成嵌套list

ltu_list = [col.tolist() for _, col in ltu_df.iterrows()]

也就是对数据进行遍历的方法
for index, row in data.iterrows()
Note: 也对index进行了遍历。

pandas.dataframe转换成numpy.ndarray

rat_array = rat_mat_df.values

存在的坑:

l_array = df['VenueLocation'].map(lambda s: np.array(s.split(','))).values

print(type(l_array))

print(l_array.shape)

<class 'numpy.ndarray'>
(483805,)而不是(483805, 2)

原因在于转换后array中的元素不是当成两列,而是一列,也就是将两个元素当成了一个列表或者array元素,只有一列了。进行数据转换时l_array.astype(float)就会出错:ValueError: setting an array element with a sequence。这里最好使用l_array = np.array([s.split(',') for s in l_array]).astype(float)。

dataframe数据类型转换

使用 DataFrame.dtypes 可以查看每列的数据类型,Pandas默认可以读出int和float64,其它的都处理为object,需要转换格式的一般为日期时间。

DataFrame.astype() 方法可对整个DataFrame或某一列进行数据格式转换,支持Python和NumPy的数据类型。

Having specific dtypes. The main types stored in pandas objects are float, int, bool,datetime64[ns] and datetime64[ns, tz] (in >= 0.17.0), timedelta[ns],category and object. In addition these dtypes have item sizes, e.g.int64 and int32. 其它参数参考官网。

data_df['case_id'] = data_df['case_id'].astype('int64').astype('str')

查看数据

See the top & bottom rows of the frame

In [14]: df.head()
Out[14]: 
                   A         B         C         D
2013-01-01  0.469112 -0.282863 -1.509059 -1.135632
2013-01-02  1.212112 -0.173215  0.119209 -1.044236
2013-01-03 -0.861849 -2.104569 -0.494929  1.071804
2013-01-04  0.721555 -0.706771 -1.039575  0.271860
2013-01-05 -0.424972  0.567020  0.276232 -1.087401

In [15]: df.tail(3)
Out[15]: 
                   A         B         C         D
2013-01-04  0.721555 -0.706771 -1.039575  0.271860
2013-01-05 -0.424972  0.567020  0.276232 -1.087401
2013-01-06 -0.673690  0.113648 -1.478427  0.524988

Display the index, columns, and the underlying numpy data

dataframe数据遍历和迭代iteration

  • for i in obj 方式,对不同数据结构不同;遍历的只是df的columns names

    • Series : 代表值
    • DataFrame : 代表列label,即列名
    • Panel : item label
  • .iteriems(),对DataFrame相当于对列迭代。

    • Series: (index, value)
    • DataFrame : (column, Series)
    • Panel : (item, DataFrame)
  • df.iterrow(),对DataFrame的每一行进行迭代,返回一个Tuple (index, Series)

  • df.itertuples(),也是一行一行地迭代,返回的是一个namedtuple,通常比iterrow快,因为不需要做转换
for idx, row in df.iterrows():
    print idx, row

for row in df.itertuples():
    print row

for c, col in df.iteritems():
    print c, col

查看数据行列数

pandas返回整个dataframe数据的个数:df.size
pandas返回dataframe行数可能最快的方式:df.shape[0]

pandas返回dataframe列数:df.shape[1] 或者df.columns.size

[how to get row count of pandas dataframe?]

数据类型

Having specific dtypes

In [12]: df2.dtypes
Out[12]: 
A           float64
B    datetime64[ns]
C           float32
D             int32
E          category
F            object
dtype: object

[Data Structure Intro section]

列columns和行index的名字及数据值的查看values

在R语言中,数据列和行的名字通过colnames和rownames来分别进行提取。在Python中,我们则使用columns和index属性来提取。

In [16]: df.index
Out[16]: 
DatetimeIndex(['2013-01-01', '2013-01-02', '2013-01-03', '2013-01-04',
               '2013-01-05', '2013-01-06'],
              dtype='datetime64[ns]', freq='D')

In [17]: df.columns
Out[17]: Index([u'A', u'B', u'C', u'D'], dtype='object')

像Series一样, values 属性返回一个包含在DataFrame中的数据的二维ndarray:

In [18]: df.values
Out[18]: 
array([[ 0.4691, -0.2829, -1.5091, -1.1356],
       [ 1.2121, -0.1732,  0.1192, -1.0442],
       [-0.8618, -2.1046, -0.4949,  1.0718],
       [ 0.7216, -0.7068, -1.0396,  0.2719],
       [-0.425 ,  0.567 ,  0.2762, -1.0874],
       [-0.6737,  0.1136, -1.4784,  0.525 ]])

如果DataFrame各列的数据类型不同,则值数组的数据类型就会选用能兼容所有列的数据类型:

In [67]: frame2.values
Out[67]:
array([[2000, Ohio, 1.5, nan],
       [2001, Ohio, 1.7, -1.2],
       [2002, Ohio, 3.6, nan],
       [2001, Nevada, 2.4, -1.5],
       [2002, Nevada, 2.9, -1.7]], dtype=object)

indexcolumnsname

如果一个DataFrame的 indexcolumns 有它们的 name ,也会被显示出来:

In [64]: frame3.index.name = 'year'; frame3.columns.name = 'state'
In [65]: frame3
Out[65]:
state Nevada Ohio
year
2000     NaN  1.5
2001     2.4  1.7
2002     2.9  3.6

在列名修改

s_group.columns = ['#user']

dataframe值的修改setting

修改方法有:

df['F'] = s1
df.at[dates[0],'A'] = 0
df.iat[0,1] = 0
df.loc[:,'D'] = np.array([5] * len(df))

列的修改和赋值

列可以通过赋值来修改。例如,空的 ‘debt’ 列可以通过一个纯量或数组来赋值:

In [46]: frame2['debt'] = 16.5
In [47]: frame2
Out[47]:
      year state  pop debt
one   2000 Ohio   1.5 16.5
two   2001 Ohio   1.7 16.5
three 2002 Ohio   3.6 16.5
four  2001 Nevada 2.4 16.5
five  2002 Nevada 2.9 16.5
In [48]: frame2['debt'] = np.arange(5.)
In [49]: frame2
Out[49]:
      year state  pop debt
one   2000 Ohio   1.5 0
two   2001 Ohio   1.7 1
three 2002 Ohio   3.6 2
four  2001 Nevada 2.4 3
five  2002 Nevada 2.9 4
#没有第6列,增加第6列
df[6] = np.select([y_score < 0.0, y_score > 1.0, True], [0.0, 1.0, y_score])

通过列表或数组给一列赋值时,所赋的值的长度必须和DataFrame的长度相匹配。

如果你使用Series来赋值,它会代替在DataFrame中精确匹配的索引的值,并在说有的空洞插入丢失数据:

In [50]: val = Series([-1.2, -1.5, -1.7], index=['two', 'four', 'five'])
In [51]: frame2['debt'] = val
In [52]: frame2
Out[52]:
      year state  pop  debt
one   2000 Ohio   1.5  NaN
two   2001 Ohio   1.7  -1.2
three 2002 Ohio   3.6  NaN
four  2001 Nevada 2.4  -1.5
five  2002 Nevada 2.9  -1.7

给一个不存在的列赋值,将会创建一个新的列。

In [53]: frame2['eastern'] = frame2.state == 'Ohio'
In [54]: frame2
Out[54]:
      year  state pop   debt eastern
one   2000   Ohio 1.5    NaN    True
two   2001   Ohio 1.7   -1.2    True
three 2002   Ohio 3.6    NaN    True
four  2001 Nevada 2.4   -1.5   False
five  2002 Nevada 2.9   -1.7   False

像字典一样 del 关键字将会删除列:

In [55]: del frame2['eastern']
In [56]: frame2.columns
Out[56]: Index([year, state, pop, debt], dtype=object)

将dataframe的一列column分割成两列column

ltu_df = ltu_df['VenueLocation'].apply(lambda s: pd.Series([float(i) for i in s.split(',')])).join(ltu_df).drop('VenueLocation', axis=1)

[pandas: How do I split text in a column into multiple rows?]

或者

df = pd.concat([df, dates.apply(lambda x: pd.Series(json.loads(x)))], axis=1, ignore_index=True)

[Python pandas.read_csv split column into multiple new columns using comma to separate]

或者

lista = [item.split(' ')[2] for item in df['Fecha']]
listb = p.Series([item.split(' ')[0] for item in df['Fecha']])
df['Fecha'].update(listb)
df['Hora'] = lista

[How split a column in two colunms in pandas]

将dataframe的两列column合并成一列column

In [10]: df
          A         B       lat      long
0  1.428987  0.614405  0.484370 -0.628298
1 -0.485747  0.275096  0.497116  1.047605
In [11]: df['lat_long'] = df[['lat', 'long']].apply(tuple, axis=1)
In [12]: df
          A         B       lat      long                             lat_long
0  1.428987  0.614405  0.484370 -0.628298      (0.484370195967, -0.6282975278)
1 -0.485747  0.275096  0.497116  1.047605      (0.497115615839, 1.04760475074)

Note: apply里面如果使用list来合并会失败,df并不会有任何改变,目前lz还没发现什么原因。
合并两列当然还可以使用np.dstack和zip等等方法。
[How to form tuple column from two columns in Pandas]

pandas.dataframe值替换

DataFrame.replace(to_replace=None, value=None, inplace=False, limit=None, regex=False, method='pad', axis=None)

参数to_replace : str, regex, list, dict, Series, numeric, or None

    dict: Nested dictionaries, e.g., {‘a’: {‘b’: nan}}, are read asfollows: look in column ‘a’ for the value ‘b’ and replace itwith nan. You can nest regular expressions as well. Note thatcolumn names (the top-level dictionary keys in a nesteddictionary) cannot be regular expressions.
            Keys map to column names and values map to substitutionvalues. You can treat this as a special case of passing twolists except that you are specifying the column to search in.

ui_rec_df.replace({0: item_names_dict}, inplace=True)

不过字典的方法只能一列一列的将某个值替换为另一个值。

所以还可以这样:

for key in item_names_dict:
    ui_rec_df.replace(key, item_names_dict[key], inplace=True)

要替换的值还可以是正则表达式regex : bool or same types as to_replace, default False
    Whether to interpret to_replace and/or value as regular expressions. If this is True then to_replace must be a string. Otherwise, to_replace must be None because this parameter will be interpreted as a regular expression or a list, dict, or array of regular expressions.

[pandas.DataFrame.replace]

[pandas教程:[26]值替换]


 

pandas基本功能

本节将带你穿过Series或DataFrame所包含的数据的基础结构的相互关系。

从一个坐标轴删除条目drop

对于Series

丢弃某条轴上的一个或多个项很简单,只要有一个索引数组或列表即可。由于需要执行一些数据整理和集合逻辑,所以drop方法返回的是一个在指定轴上删除了指定值的新对象:

In [94]: obj = Series(np.arange(5.), index=['a', 'b', 'c', 'd', 'e'])
In [95]: new_obj = obj.drop('c')
In [97]: obj.drop(['d', 'c'])
Out[97]:
a   0
b   1
e   4

对于DataFrame

可以从任何坐标轴删除索引值:axis 参数告诉函数到底舍弃列还是行,如果axis等于0,那么就舍弃行。

In [98]: data = DataFrame(np.arange(16).reshape((4, 4)), index=['Ohio', 'Colorado', 'Utah', 'New York'], columns=['one', 'two', 'three', 'four'])
In [99]: data.drop(['Colorado', 'Ohio'])
Out[99]:
         one two three four
Utah       8   9    10   11
New York  12  13    14   15
测试了一下,也可以使用df.drop(1)来删除行1。

In [100]: data.drop('two', axis=1)      In [101]: data.drop(['two', 'four'], axis=1) #等价于date.drop(date.columns[[1, 3]], axis = 1)
Out[100]: Out[101]:
       one   three four                            one three
Ohio     0   2        3                 Ohio         0     2
Colorado 4   6        7                 Colorado     4     6
Utah     8   10      11                 Utah         8    10
New York 12  14       15                New York    12    14

算术和数据对齐

算术运算及NA值

pandas的最重要的特性之一是在具有不同索引的对象间进行算术运算的行为。当把对象加起来时,如果有任何的索引对不相同的话,在结果中将会把各自的索引联合起来。

对于Series

>>>s1 = Series([7.3, -2.5, 3.4, 1.5],index=['a', 'c', 'd', 'e'])
>>>s2 = Series([-2.1, 3.6, -1.5, 4, 3.1], index=['a', 'c', 'e', 'f', 'g'])

>>>s1+s2
a    5.2
c    1.1
d    NaN
e    0.0
f    NaN
g    NaN
dtype: float64

内部数据对其,在索引不重合的地方引入了NA值。数据缺失在算术运算中会传播。

对于DataFrame

对其在行和列上都表现的很好:

_images/131.png

把这些加起来返回一个DataFrame,它的索引和列是每一个DataFrame对应的索引和列的联合:

_images/135.png

带填充值的算术方法

在不同索引对象间的算术运算,当一个轴标签在另一个对象中找不到时,你可能想要填充一个特定的值,如0:

_images/136.png

把它们加起来导致在不重合的位置出现NA值。

df1 上使用 add 方法,我把 df2 传递给它并给fill_value 赋了一个参数:

>>>df1.add(df2, fill_value=0)

与此类似,在对Series或DataFrame重新索引时,也可以指定一个填充值:

_images/142.png

灵活的算术方法
add 加法(+)
sub 减法(-)
div 除法(/)
mul 乘法(*)

DataFrame 和 Series 间的操作

与NumPy数组一样,很好的定义了DataFrame和Series间的算术操作。

首先,作为一个激发性的例子,考虑一个二维数组和它的一个行间的差分,这被称为 广播 (broadcasting)。

_images/143.png

在一个DataFrame和一个Series间的操作是类似的:

_images/147.png

默认的,DataFrame和Series间的算术运算Series的索引将匹配DataFrame的列,并在行上扩展

_images/151.png

如果一个索引值在DataFrame的列和Series的索引里都找不着,对象将会从它们的联合重建索引

_images/152.png

如果想在行上而不是列上进行扩展,你要使用一个算术方法。例如:

_images/154.png_images/157.png

你所传递的坐标值是将要匹配的 坐标 。这种情况下是匹配DataFrame的行,并进行扩展。

函数应用和映射

NumPy的ufuncs (元素级数组方法)用于操作pandas对象

np.abs(frame)

dataframe函数应用

apply()将一个函数作用于DataFrame中的每个行或者列,而applymap()是将函数做用于DataFrame中的所有元素(elements)。​

函数应用到由各列或行所形成的一维数组上apply

DataFrame的 apply方法即可实现此功能。许多最为常见的数组统计功能都被实现成DataFrame的方法(如sum和mean),因此无需使用apply方法。

默认对列操作(axis=0),如传入np.sum()是对每列求和。

返回标量值

>>>f = lambda x: x.max() - x.min()
>>>frame.apply(f)
>>>frame.apply(f, axis=1)

df.apply(np.cumsum)

除标量值外,传递给apply的函数还可以返回由多个值组成的Series
>>>def f(x):
return Series([x.min(), x.max()], index=['min', 'max'])
>>>frame.apply(f)

dataframe应用元素级的Python函数applymap

假如想得到frame中各个浮点值的格式化字符串,使用applymap即可。

>>>format = lambda x: '%.2f' % x
>>>frame.applymap(format)

之所以叫做applymap,是因为Series有一个用于应用元素级函数的map方法:

>>>frame['e'].map(format)

只对df的某列进行变换就取那一列的series进行变换就好了

如将时间转换成只有日期date没有时间time

user_pay_df['time']=user_pay_df['time'].apply(lambda x:x.date())

Series函数应用

Series.apply(func, convert_dtype=True, args=(), **kwds)

Invoke function on values of Series. Can be ufunc (a NumPy functionthat applies to the entire Series) or a Python function that only workson single values

 Series.map(arg, na_action=None)

    Map values of Series using input correspondence (which can be a dict, Series, or function)
与apply的区别可能就只是应用的函数更多一点吧,如示例中series map到series上。

示例

>>> x
one   1
two   2
three 3
>>> y
1  foo
2  bar
3  baz
>>> x.map(y)
one   foo
two   bar
three baz

s3 = s.map(lambda x: 'this is a string {}'.format(x),
               na_action='ignore')
0    this is a string 1.0
1    this is a string 2.0
2    this is a string 3.0
3                     NaN

排序(sorting)

根据条件对数据集排序(sorting)也是一种重要的内置运算。

对行或列索引进行排序 (按字典顺序)sort_index

sort_index方法,它将返回一个已排序的新对象
>>>obj = Series(range(4), index=['d', 'a',  'b', 'c'])
>>>obj.sort_index()
a    1
b    2
c    3
d    0
dtype: int64

按值对Series进行排序order

>>>obj = Series([4, 7, -3, 2])
>>>obj.order()
2   -3
3    2
0    4
1    7
>>>obj = Series([4, np.nan, 1, np.nan, -3, 2])
>>>obj.order() #在排序时,缺失值默认都会被放到Series的末尾.
4    -3
2     1
5     2
0     4
1   NaN
NaN

DataFrame任意轴上索引进行排序

>>>frame = DataFrame(np.arange(8).reshape((2, 4)),  index=['three', 'one'], columns=['d','a','b','c'])
>>>frame.sort_index()
>>>frame.sort_index(axis=1)
数据默认是按升序排序的,但也可以降序排序:
>>>frame.sort_index(axis=1, ascending=False)

DataFrame列的值排序

将一个或多个列的名字传递给by选项即可达到该目的:
>>>frame = DataFrame({'b': [4,7,-3,2], 'a':[0, 1, 0, 1]})
>>> frame.sort_index(by='b')    #或者df.sort_values(by='b')

要根据多个列进行排序,传入名称的列表即可:>>>frame.sort_index(by=['a', 'b'])

或者syntax of sort:

DataFrame.sort(columns=None, axis=0, ascending=True, inplace=False, kind='quicksort',na_position='last')
we will sort the data by “2013” column 
Insurance_rates.sort(['2013','State'],ascending=[1, 0])

[Data Analysis with Pandas]

排名(ranking)

跟排序关系密切,且它会增设一个排名值(从1开始,一直到数组中有 效数据的数量)。

它跟numpy.argsort产生的间接排序索引差不多,只不过它可以根据某种规则破坏平级关系。

Series和DataFrame的rank方法:默认情况下,rank是通过“为各组分配一个平均排名”的方式破坏平级关系的:
>>> obj = Series([7,-5,7,4,2,0,4])
>>>obj
0    7
1   -5
2    7
3    4
4    2
5    0
6    4
>>> print obj.rank()
0    6.5
1    1.0
2    6.5
3    4.5
4    3.0
5    2.0
6    4.5
>>> obj.rank(method='first')  #根据值在原数据中出现的顺序给出排名:
0    6
1    1
2    7
3    4
4    3
5    2
5
>>> obj.rank(ascending=False, method='max') # 按降序进行排名:
0    2
1    7
2    2
3    4
4    5
5    6
6    4

排名时用于破坏平级关系的method选项

Method                           说明
‘average’            默认:在相等分组中,为各个值分配平均排名
‘min’              使用整个分组的最小排名
‘max’             使用整个分组的最大排名
‘first’                     按值在原始数据中的出现顺序分配排名

DataFrame在行或列上计算排名

>>> frame    =DataFrame({'b': [4.3, 7, -3, 2], 'a': [0, 1, 0, 1],
'c':[-2, 5, 8, -2.5]})
>>> frame.rank(axis=1)

from:http://blog.csdn.net/pipisorry/article/details/18010307

ref:《利用Python进行数据分析》*

官网pandas: Python Data Analysis LibraryAPI Reference10 Minutes to pandas*十分钟搞定pandas   pandas 0.18.1 documentation  Essential Basic Functionality

API Reference

[Input/Output

General functions

Series

DataFrame

Panel

Panel4D

Index

CategoricalIndex

MultiIndex

DatetimeIndex

TimedeltaIndex

Window

GroupBy

Resampling

Style

General utility functions

]

pandas-cookbook

Python For Data Analysis*pandas入门  Errata for Python for Data Analysis

pandas学习笔记.md

pandas 基础

14 BEST PYTHON PANDAS FEATURES

[Python数据处理:Pandas模块的 12 种实用技巧]

[Pandas 中的坑index操作 遍历操作]

猜你喜欢

转载自blog.csdn.net/pipisorry/article/details/18010307