numpy 切片
In [8]: arr = np.array( [[1, 2], [3, 4]])
In [9]: arr
Out[9]:
array([[1, 2],
[3, 4]])
In [10]: arr[0] # 取第一行
Out[10]: array([1, 2])
In [11]: arr[:, 1] # 取第二列, 用逗号隔开表示第二个切片或者索引,就像一个tuple2,第二个切片来表示y轴
Out[11]: array([2, 4])
pandas 如果直接对DataFrame进行切片,只能操作行,如果还要操作列需要使用pd.DataFrame.iloc
:
In [24]: df = pd.DataFrame(data=[[1,2], [3,4]])
In [25]:
In [25]: df[:1]
Out[25]:
0 1
0 1 2
In [27]: df[:1] # 取第一行
Out[27]:
0 1
0 1 2
In [28]: df[:1, 1] # 如果要取列则报错,需要使用iloc
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
<ipython-input-28-e53f18cf1f5d> in <module>
----> 1 df[:1, 1]
~/miniconda3/envs/cooka/lib/python3.7/site-packages/pandas/core/frame.py in __getitem__(self, key)
3022 if self.columns.nlevels > 1:
3023 return self._getitem_multilevel(key)
-> 3024 indexer = self.columns.get_loc(key)
3025 if is_integer(indexer):
3026 indexer = [indexer]
~/miniconda3/envs/cooka/lib/python3.7/site-packages/pandas/core/indexes/range.py in get_loc(self, key, method, tolerance)
352 except ValueError as err:
353 raise KeyError(key) from err
--> 354 raise KeyError(key)
355 return super().get_loc(key, method=method, tolerance=tolerance)
356
KeyError: (slice(None, 1, None), 1)
In [29]: df.iloc[:1, 1] # 使用iloc可以操作行或者列
Out[29]:
0 2
Name: 1, dtype: int64