Pandas 按元组重命名单行 MultiIndex [英] Pandas Rename a Single Row of MultiIndex by Tuple
问题描述
我正在尝试通过元组重命名熊猫数据框的单行.
I'm trying to rename a single row of a pandas dataframe by it's tuple.
例如:
import pandas as pd
df = pd.DataFrame(data={'i1':[0,0,0,0,1,1,1,1],
'i2':[0,1,2,3,0,1,2,3],
'x':[1.,2.,3.,4.,5.,6.,7.,8.],
'y':[9,10,11,12,13,14,15,16]})
df.set_index(['i1','i2'], inplace=True)
创建df:
x y
i1 i2
0 0 1.0 9
1 2.0 10
2 3.0 11
3 4.0 12
1 0 5.0 13
1 6.0 14
2 7.0 15
3 8.0 16
我希望能够使用类似:df.rename(index={(0,1):(0,9)},inplace=True)
来获取:
I'd like to be able to use something like: df.rename(index={(0,1):(0,9)},inplace=True)
to get:
x y
i1 i2
0 0 1.0 9
9 2.0 10 <-- new key
2 3.0 11
3 4.0 12
1 0 5.0 13
1 6.0 14
2 7.0 15
3 8.0 16
该命令执行时不会引发错误,但返回相同的 df 不变.
The command executes without raising an error but returns the same df unchanged.
这也返回相同的 df:df.rename(index={pd.IndexSlice[0,1]:pd.IndexSlice[0,9]},inplace=True)
This also returns the same df: df.rename(index={pd.IndexSlice[0,1]:pd.IndexSlice[0,9]},inplace=True)
这将接近预期的效果:
df.loc[(0,9),:] = df.loc[(0,1),:]
df.drop(index=(0,1),inplace=True)
但如果行排序很重要,那么将其调整为正确的顺序会很痛苦,如果 df 变大可能会很慢.
but if row ordering matters, it'll be a pain to get it into the right order, and possibly quite slow if the df gets big.
我使用的是 Pandas 1.0.1,python 3.7.有什么建议么?提前致谢.
I'm using Pandas 1.0.1, python 3.7. Any suggestions? Thank you in advance.
推荐答案
具有列表理解和 MultiIndex.from_tuples
:
Possible solution with list comprehension and MultiIndex.from_tuples
:
L = [(0,9) if x == (0,1) else x for x in df.index]
df.index = pd.MultiIndex.from_tuples(L, names=df.index.names)
print (df)
x y
i1 i2
0 0 1.0 9
9 2.0 10
2 3.0 11
3 4.0 12
1 0 5.0 13
1 6.0 14
2 7.0 15
3 8.0 16
这篇关于Pandas 按元组重命名单行 MultiIndex的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!