使用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. glob/globfree--找出匹配模式的路径名

    语法 #include <glob.h> int glob(const char *pattern, int flags, int (*errfunc) (const char *epat ...

  2. Swift培训

    本篇是Swift内部培训整理的PPT材料,主要内容来源于苹果Swift编程语言官方教程,参考了网上的一些视频课程内容.在教程介绍完之后,本人附带实现了一个项目开发中的常用场景的Demo:基于导航栏和T ...

  3. linux split

    说来惭愧,用了这么久linux会的命令也只有常用的那么几个.. 今天刚刚学到的一个很实用的split命令,原本就只是知道开发语言中有split方法用来切分字符串,linux命令行也提供了这样一个方法. ...

  4. C0302 将一个代码块中的内容保存在文件中, 查看一个rpm包是否可以安装

    #!/bin/bash # 这个脚本是用来描述和确认是否可以安装一个rpm包 # 在一个文件中保存输出 SUCCESS=0 E_NOARGS=65 if [ -z "$1" ] t ...

  5. linux输入法

    sudo apt-get install fcitx-table-wbpy安装fcitx 中文是灰色的就拖到第一个 桌面右上角有个设置,可以添加拼音 拼音特别难用

  6. Struts1中actionform和action属于MVC哪一层,为什么?

    Struts1中actionform和action属于MVC哪一层,为什么? 解答:actionform和action属于MVC的Model层,Action用来处理业务逻辑,actionform保存用 ...

  7. CH Round #55 - Streaming #6 (NOIP模拟赛day2)(被虐哭)

    http://ch.ezoj.tk/contest/CH%20Round%20%2355%20-%20Streaming%20%236%20%28NOIP%E6%A8%A1%E6%8B%9F%E8%B ...

  8. js 代码风格(2)

    Properties    • 当访问属性的时候,我们使用点(.)操作符. var luke = { jedi: true, age: 28 }; // bad var isJedi = luke[' ...

  9. cout显示Mat类对象报错Access Violation

    AV(Access Violation)错误:非法访问. image_match.exe 中的 0x0000002a 处有未经处理的异常: 0xC0000005: Access violation 程 ...

  10. 【转】JavaScript和Java的区别

    虽然JavaScript与Java有紧密的联系,但却是两个公司开发的不同的两个产品.      Java是SUN公司推出的新一代面向对象的程序设计语言,特别适合于Internet 应用程序开发:而Ja ...