對于以下數據框:d = {'a':[10,11,12,13],'b':[20,21,22,23], 'c':[30,31,32,33]}pd_df = pd.DataFrame(d)pd_df.set_index('a') b ca 10 20 3011 21 3112 22 3213 23 33這段代碼pd_df.loc[10]給出以下錯誤:~/.local/lib/python3.6/site-packages/pandas/core/indexing.py in _validate_key(self, key, axis) 1789 if not ax.contains(key):-> 1790 error() 1791 except TypeError as e:~/.local/lib/python3.6/site-packages/pandas/core/indexing.py in error() 1784 .format(key=key,-> 1785 axis=self.obj._get_axis_name(axis))) 1786 KeyError: 'the label [10] is not in the [index]'我該如何修復它?
1 回答

喵喵時光機
TA貢獻1846條經驗 獲得超7個贊
如果要將索引設置為a,請執行以下操作:
d = {'a':[10,11,12,13],'b':[20,21,22,23], 'c':[30,31,32,33]}
pd_df = pd.DataFrame(d)
pd_df = pd_df.set_index('a') ## <<< CHANGE HERE
然后
pd_df.loc[10]
輸出:
b 20
c 30
Name: 10, dtype: int64
添加回答
舉報
0/150
提交
取消