pd.__version__
'0.15.2'
我有一个熊猫的数据框,它具有三个级别的多索引。当我连接两个数据帧时,它将最低的索引转换为一个浮点数,它应该是一个字符串。
idx=str(dfmaster_stats.index.levels[2]).replace('.0', '')
TypeError: 'FrozenList' does not support mutable operations.
我查看了其他问题,发现无法更改多个索引,因此我尝试为数据框重新编制索引。我关注了这个问题,但是两种解决方案均无效。
我也尝试过set_levels,但不确定语法。
dfmaster_stats.index.set_levels(dfmaster_stats.index.levels[2](idx), level =2)
给我这个错误
TypeError: 'Index' object is not callable
就像其他文章中提到的那样,重置索引,更改dtype和设置新索引可能会更容易。
np.random.seed(0)
tuples = list(zip(*[['bar', 'bar', 'baz', 'baz',
'foo', 'foo', 'qux', 'qux'],
[1.0, 2.0, 1.0, 2.0,
1.0, 2.0, 1.0, 2.0]]))
idx = pd.MultiIndex.from_tuples(tuples, names=['first', 'second'])
df = pd.DataFrame(np.random.randn(8, 2), index=idx, columns=['A', 'B'])
print(df)
print(df.index.get_level_values("second").dtype)
输出:
A B
first second
bar 1.0 1.764052 0.400157
2.0 0.978738 2.240893
baz 1.0 1.867558 -0.977278
2.0 0.950088 -0.151357
foo 1.0 -0.103219 0.410599
2.0 0.144044 1.454274
qux 1.0 0.761038 0.121675
2.0 0.443863 0.333674
float64
现在,重置索引,更改dtype并设置新索引。
df = df.reset_index()
df["second"] = df["second"].astype(int).astype(str)
df = df.set_index(["first", "second"])
print(df)
print(df.index.get_level_values("second").dtype)
输出:
A B
first second
bar 1 1.764052 0.400157
2 0.978738 2.240893
baz 1 1.867558 -0.977278
2 0.950088 -0.151357
foo 1 -0.103219 0.410599
2 0.144044 1.454274
qux 1 0.761038 0.121675
2 0.443863 0.333674
object
总的来说,我发现操纵多索引(索引?)有时值得,而有时却不值得。更改级别变得冗长。如果您致力于原因,那么可以这样做:
idx0 = df.index.levels[0]
idx1 = df.index.levels[1].astype(str).str.replace('.0', '')
df.index = df.index.set_levels([idx0, idx1])
print(df.index.levels[1].dtype)
输出:
object
如果您提供用于创建数据框的示例代码,我可以将其扩展到3个级别,也可以解决。:)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句