我试图通过它的元组重命名 pandas 数据框的单行。
例如:
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)
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 不变。
这也返回相同的 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 变大,速度可能会很慢。
我正在使用 Pandas 1.0.1,python 3.7。有什么建议么?先感谢您。