python - 修复代码以摆脱 ValueError : cannot set using a multi-index selection indexer with a different length

标签 python pandas

当我尝试根据另一列的值有条件地更新数据框列时,出现以下错误。

ValueError: cannot set using a multi-index selection indexer with a different length than the value.

我花了几个小时也没能找出原因。以下是演示该问题的简化代码:

dfm = pd.DataFrame({'jim': [0, 0, 1, 1],
                    'joe': ['x', 'y', 'z', 'y'],
                    'jolie': np.random.rand(4), 
                    'folie': np.random.rand(4)})

dfm = dfm.set_index(['jim', 'joe'])

dfm.loc[(dfm['jolie'] == 1) , 'jolie'] = dfm['folie']

一旦我删除了索引,上面最后一行代码就可以工作了。我的问题是:我做错了什么?上面的代码可以在不删除索引的情况下修复吗?这是 Pandas 的错误​​吗? 非常感谢您的帮助。

最佳答案

这里的问题很可能是因为 dfm.loc[(dfm['jolie'] == 1) , 'jolie'] 的长度与 dfm 的长度不同['folie'] 因为前者只查看 dfm['jolie'] 的一个子系列。

另外,在给一个series赋值时,两者的索引必须匹配,无论是单索引还是多索引。

例如,以下将起作用:

dfm.loc[(dfm['jolie'] == 1) , 'jolie'] = dfm.loc[(dfm['jolie'] == 1) ,'folie']

关于python - 修复代码以摆脱 ValueError : cannot set using a multi-index selection indexer with a different length,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55543097/

相关文章:

python - 查找列表集合中变量的概率

python - Django REST 浏览器界面

python - 从单个字符串到 1 列 DataFrame?

python - 使用 nltk 计算 pandas Dataframe 中最流行的 'two words combination' 希伯来语单词

python - Pandas ,根据某些列值和 NAN 组合行

python - Twisted 中的单元测试客户端-服务器交互

python - 如何从 tox 控制台输出中隐藏已安装的 deps 列表?

python - 为什么 Python 没有静态变量?

python - reshape 序列 Numpy Pandas python

python - 从多个数据框中删除多列