为了账号安全,请及时绑定邮箱和手机立即绑定

如何在Python中使用loc[]

如何在Python中使用loc[]

弑天下 2023-12-26 15:53:48
对于以下数据框: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


查看完整回答
反对 回复 2023-12-26
  • 1 回答
  • 0 关注
  • 45 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信