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

尝试将列设置为 pandas 数据框中的索引时出错

尝试将列设置为 pandas 数据框中的索引时出错

红糖糍粑 2023-12-26 14:54:00
我有以下代码:A = pd.DataFrame([[1, 2], [1, 3], [4, 6]], columns=[['att1', 'att2']]) A['idx'] = ['a', 'b', 'c'] A在我这样做之前它工作正常(尝试将列“idx”设置为数据帧的索引)A.set_index('idx', inplace=True)这会引发错误TypeError: only integer scalar arrays can be converted to a scalar index这是什么意思 ?
查看完整描述

1 回答

?
梵蒂冈之花

TA贡献1900条经验 获得超5个赞

错误是当你创建A时


columns = [['att1', 'att2']]

如果你打印A.columns你会得到:


MultiIndex([('att1',),

            ('att2',),

            ( 'idx',)],

           )

所以'idx'并不是真正在你的列中供你设置索引。现在,这可以工作:


A.set_index(('idx',))

并给出:


       att1 att2

(idx,)          

a         1    2

b         1    3

c         4    6

A但是,您应该仅使用以下命令来修复您的创建:


columns = ['att1', 'att2']


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

添加回答

举报

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