# 添加列,匹配式添加
frame2['debt']=16.5
frame2['debt']= np.arange(6.)
val = pd.Series([-1.2,-1.5,-1.7], index=['two','four','five'])
frame2['debt']= val
frame2
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
six
2003
Nevada
3.2
NaN
frame2["eastern"]=frame2.state =='Ohio'
frame2
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
six
2003
Nevada
3.2
NaN
False
# 删除列del frame2['eastern']
frame2
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
six
2003
Nevada
3.2
NaN
frame2.iloc[0:3,0:2]
year
state
one
2000
Ohio
two
2001
Ohio
three
2002
Ohio
frame2.loc["one":"three","year":"state"]
year
state
one
2000
Ohio
two
2001
Ohio
three
2002
Ohio
ser = pd.Series(np.arange(3.))
ser[-1]
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
File d:\Anaconda3\envs\guoguo\lib\site-packages\pandas\core\indexes\range.py:391, in RangeIndex.get_loc(self, key, method, tolerance)
390 try:
--> 391 return self._range.index(new_key)
392 except ValueError as err:
ValueError: -1 is not in range
The above exception was the direct cause of the following exception:
KeyError Traceback (most recent call last)
d:\ai_py_3.9\常用代码\pfda\chapter5.ipynb Cell 38 line 2
<a href='vscode-notebook-cell:/d%3A/ai_py_3.9/%E5%B8%B8%E7%94%A8%E4%BB%A3%E7%A0%81/pfda/chapter5.ipynb#X51sZmlsZQ%3D%3D?line=0'>1</a> ser = pd.Series(np.arange(3.))
----> <a href='vscode-notebook-cell:/d%3A/ai_py_3.9/%E5%B8%B8%E7%94%A8%E4%BB%A3%E7%A0%81/pfda/chapter5.ipynb#X51sZmlsZQ%3D%3D?line=1'>2</a> ser[-1]
File d:\Anaconda3\envs\guoguo\lib\site-packages\pandas\core\series.py:981, in Series.__getitem__(self, key)
978 return self._values[key]
980 elif key_is_scalar:
--> 981 return self._get_value(key)
983 if is_hashable(key):
984 # Otherwise index.get_value will raise InvalidIndexError
985 try:
986 # For labels that don't resolve as scalars like tuples and frozensets
File d:\Anaconda3\envs\guoguo\lib\site-packages\pandas\core\series.py:1089, in Series._get_value(self, label, takeable)
1086 return self._values[label]
1088 # Similar to Index.get_value, but we do not fall back to positional
-> 1089 loc = self.index.get_loc(label)
1090 return self.index._get_values_for_loc(self, loc, label)
File d:\Anaconda3\envs\guoguo\lib\site-packages\pandas\core\indexes\range.py:393, in RangeIndex.get_loc(self, key, method, tolerance)
391 return self._range.index(new_key)
392 except ValueError as err:
--> 393 raise KeyError(key) from err
394 self._check_indexing_error(key)
395 raise KeyError(key)
KeyError: -1