【发布时间】:2020-06-29 09:52:42
【问题描述】:
给定一个具有多索引列的 DataFrame
import pandas as pd
fish = [("Fish", lli) for lli in ["One", "Two"]]
dogs = [("Dog", lli) for lli in ["Three", "Four", "Five"]]
cats = [("Cat", lli) for lli in ["Three", "Four", "Five"]]
df = pd.DataFrame(index=["Blue", "Green", "Red"], columns=pd.MultiIndex.from_tuples(fish+dogs+cats))
-
df =
Fish Dog Cat
One Two Three Four Five Three Four Five
Blue NaN NaN NaN NaN NaN NaN NaN NaN
Green NaN NaN NaN NaN NaN NaN NaN NaN
Red NaN NaN NaN NaN NaN NaN NaN NaN
现在我想同时设置两列的值,例如
df.loc[:, ('Dog', ['Four', 'Five'])] = 3.1
这会导致 KeyError 说
KeyError: 'MultiIndex Slicing requires the index to be fully lexsorted tuple len (2), lexsort depth (0)'
可以通过在使用设置值之前对列进行排序来“解决”问题
df = df.sort_index(axis=1)
现在的问题是我不想对列进行排序,因为它们已经以反映所需输出的方式排序。 有没有什么办法不先排序就设置多列的值?
【问题讨论】:
-
你的熊猫版本是什么?
-
这似乎在版本
'1.0.0'中工作 -
对我来说工作得很好,我认为有必要升级 pandas
-
我在 0.19.1,无法升级。
标签: python pandas dataframe sorting multi-index