使用pandas创建一个对象

In [1]: import pandas as pd

In [2]: import numpy as np

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

In [4]: df
Out[4]:
A B C D
2018-01-01 -0.603510 0.269480 0.197354 -0.433003
2018-01-02 1.230502 0.474616 1.473517 -0.627363
2018-01-03 -0.402034 0.569097 0.675872 -0.317995
2018-01-04 0.220638 0.527543 -1.140620 -0.348089
2018-01-05 -2.494331 0.593269 0.596578 1.653347
2018-01-06 -2.766239 -0.919777 0.462890 0.156048

如果你想得到第三行的数据:

如果你沿袭之前python切片的习惯,想直接取,那么需要改变一下方式。

KeyError                                  Traceback (most recent call last)
D:\Anaconda3\lib\site-packages\pandas\core\indexes\base.py in get_loc(self, key, method, tolerance)
3062 try:
-> 3063 return self._engine.get_loc(key)
3064 except KeyError: pandas\_libs\index.pyx in pandas._libs.index.IndexEngine.get_loc() pandas\_libs\index.pyx in pandas._libs.index.IndexEngine.get_loc() pandas\_libs\hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item() pandas\_libs\hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item() KeyError: 2 During handling of the above exception, another exception occurred: KeyError Traceback (most recent call last)
<ipython-input-5-b5f2749c85df> in <module>()
----> 1 df[2] D:\Anaconda3\lib\site-packages\pandas\core\frame.py in __getitem__(self, key)
2683 return self._getitem_multilevel(key)
2684 else:
-> 2685 return self._getitem_column(key)
2686
2687 def _getitem_column(self, key): D:\Anaconda3\lib\site-packages\pandas\core\frame.py in _getitem_column(self, key)
2690 # get column
2691 if self.columns.is_unique:
-> 2692 return self._get_item_cache(key)
2693
2694 # duplicate columns & possible reduce dimensionality D:\Anaconda3\lib\site-packages\pandas\core\generic.py in _get_item_cache(self, item)
2484 res = cache.get(item)
2485 if res is None:
-> 2486 values = self._data.get(item)
2487 res = self._box_item_values(item, values)
2488 cache[item] = res D:\Anaconda3\lib\site-packages\pandas\core\internals.py in get(self, item, fastpath)
4113
4114 if not isna(item):
-> 4115 loc = self.items.get_loc(item)
4116 else:
4117 indexer = np.arange(len(self.items))[isna(self.items)] D:\Anaconda3\lib\site-packages\pandas\core\indexes\base.py in get_loc(self, key, method, tolerance)
3063 return self._engine.get_loc(key)
3064 except KeyError:
-> 3065 return self._engine.get_loc(self._maybe_cast_indexer(key))
3066
3067 indexer = self.get_indexer([key], method=method, tolerance=tolerance) pandas\_libs\index.pyx in pandas._libs.index.IndexEngine.get_loc() pandas\_libs\index.pyx in pandas._libs.index.IndexEngine.get_loc() pandas\_libs\hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item() pandas\_libs\hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item() KeyError: 2

df[2]存在语法错误

正确的做法其实有好多种:

方法1:

In [6]: df[2:3]
Out[6]:
A B C D
2018-01-03 -0.402034 0.569097 0.675872 -0.317995

方法2:

vIn [7]: df['':'']  #这里必须使用这种方式,不然会有语法错误
Out[7]:
A B C D
2018-01-03 -0.402034 0.569097 0.675872 -0.317995

刚才使用类似python单个切片的方式貌似不行,所以就要说到今天的重点,loc、iloc、ix

(1).loc:按照标签进行取值

In [8]: df.loc['2018/01/03']
Out[8]:
A -0.402034
B 0.569097
C 0.675872
D -0.317995
Name: 2018-01-03 00:00:00, dtype: float64

(2).iloc:按照标签进行取值

In [9]: df.iloc[2]
Out[9]:
A -0.402034
B 0.569097
C 0.675872
D -0.317995
Name: 2018-01-03 00:00:00, dtype: float64

(3)ix:混合缩影

In [10]: df.ix['2018/01/03']
Out[10]:
A -0.402034
B 0.569097
C 0.675872
D -0.317995
Name: 2018-01-03 00:00:00, dtype: float64 In [11]: df.ix[2]
Out[11]:
A -0.402034
B 0.569097
C 0.675872
D -0.317995
Name: 2018-01-03 00:00:00, dtype: float64

loc、iloc、ix比较的更多相关文章

  1. Pandas:loc iloc ix用法

    参考:Pandas中关于 loc \ iloc \ ix 用法的理解 相同点 使用形式都是 df.xxx[ para1 , para2 ] #xxx表示loc iloc ix#df表示一个DataFr ...

  2. pandas 定位 loc,iloc,ix

    In [114]: df Out[114]: A B C D 2018-06-30 0.318501 0.613145 0.485612 0.918663 2018-07-31 0.614796 0. ...

  3. Pandas的 loc iloc ix 区别

    先看代码: In [46]: import pandas as pd In [47]: data = [[1,2,3],[4,5,6]] In [48]: index = [0,1] In [49]: ...

  4. pandas的loc, iloc, ix的操作

    参考: https://blog.csdn.net/xw_classmate/article/details/51333646 1. loc——通过行标签索引行数据 2. iloc——通过行号获取行数 ...

  5. Pandas之loc\iloc\ix

    ---------------------------------------------------------------------------------------------------- ...

  6. python pandas 中 loc & iloc 用法区别

    转自:https://blog.csdn.net/qq_21840201/article/details/80725433 ### 随机生DataFrame 类型数据import pandas as ...

  7. loc() iloc() at() iat()函数

    1 四个函数都是用于dataframe的定位 []用于直接定位. loc()函数是用真实索引,iloc()函数是用索引序号. loc()函数切片是左闭右闭,iloc()函数切片是左闭右开. at(), ...

  8. pandas 选取数据 修改数据 loc iloc []

    pandas选取数据可以通过 loc iloc  [] 来选取 使用loc选取某几列: user_fans_df = sample_data.loc[:,['uid','fans_count']] 使 ...

  9. pandas中Dataframe的查询方法([], loc, iloc, at, iat, ix)

    数据介绍 先随机生成一组数据: import pandas as pd import numpy as np state = ['Ohio', 'Ohio', 'Ohio', 'Nevada', 'N ...

  10. 学习笔记6—pandas中ix,loc,iloc有什么区别?

    直接看例子: >>> data = pd.Series(np.arange(10), index=[49,48,47,46,45, 1, 2, 3, 4, 5]) >>& ...

随机推荐

  1. git 工作模式

    个人在学习Git工作流的过程中,从原有的 SVN 模式很难完全理解Git的协作模式,直到有一天我看到了下面的文章,好多遗留在心中的困惑迎刃而解: 我们以使用SVN的工作流来使用Git有什么不妥? Gi ...

  2. SWT将系统图标保存为本地文件

    public class SWTImage {     public static void main(String[] args) {         final Display display = ...

  3. CSS Transform / Transition / Animation 属性的区别

    back21 Jun 2011 Category: tech Tags: css 最近想UI的动画转到css3能吃进3d加速的属性上面来以加强动画的连贯性.只是对于css几个新加的属性不太熟悉,常常容 ...

  4. Centos7安装Apache Http服务器无法访问如何解决

    1. 安装Apache组件 [root@mycentos shell]# yum install httpd 2. 安装成功后,检测有无httpd进程 [root@mycentos shell]# p ...

  5. IDEA中如何配置Tomcat和项目?

    IDEA是我用的挺多的一款java代码编辑工具,对于刚接触这款软件的新手来说,配置项目是很麻烦的了,更别说配置服务器Tomcat了,那么通过我的教程大家一定觉得配置IDEA项目也是很轻松的事了.   ...

  6. Batch Normailzation

    转自:http://blog.csdn.net/malefactor/article/details/51476961

  7. SQL Server 2008 SP3简体中文版官方下载

    微软日前公开发布了SQL Server 2008 SP3,用户可以从微软下载中心获取SP服务包和功能包升级.SP3主要包括自SQL Server 2008 SP2以来的累积更新,修复了用户反馈的一些问 ...

  8. java web 页面提速

    记得面试现在这份工作的时候,一位领导语重心长地谈道——当今的世界是互联网的世界,IT企业之间的竞争是很激烈的,如果一个网页的加载和显示速度,相比别人的站点页面有那么0.1秒的提升,那也是很大的一个成就 ...

  9. 把xml格式的字符串写入到一个xml文件中

    package demo; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; impo ...

  10. 58、常规控件(1)Floating Action Button-浮动的圆形按钮

               <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xml ...