Pandas多索引将Float更改为String

2024-09-24 06:23:59 发布

您现在位置:Python中文网/ 问答频道 /正文

pd.__version__
'0.15.2'

我有一个熊猫的数据框架,有三个层次的多重索引。当我连接这两个数据帧时,它将最低的索引变成了一个应该是字符串的float。 enter image description here

enter image description here 我试图用什么都不使用来替换.0

idx=str(dfmaster_stats.index.levels[2]).replace('.0', '')

enter image description here 把它分配给数据帧,但是我得到了这个错误

TypeError: 'FrozenList' does not support mutable operations.

我研究了其他问题,发现多索引是不能更改的,所以我尝试重新索引数据帧。我遵循了这个问题,但两种解决方案都不起作用。你知道吗

Pandas: Modify a particular level of Multiindex

它看起来绝对不对。我做错什么了? enter image description here

我也试过设置\u级别,但不确定语法。你知道吗

dfmaster_stats.index.set_levels(dfmaster_stats.index.levels[2](idx), level =2)

给我这个错误

TypeError: 'Index' object is not callable

Tags: 数据字符串框架indexversionstats错误not
1条回答
网友
1楼 · 发布于 2024-09-24 06:23:59

正如在其他文章中提到的,只需重置索引、更改数据类型和设置新索引可能会更容易。你知道吗

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

现在,重置索引,更改数据类型,并设置新索引。你知道吗

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

一般来说,我发现操纵多索引(index?)有时值得,有时不值得。更改级别会变得冗长。如果你致力于这项事业,这是可行的:

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个级别,或者您可以解决它。:)

相关问题 更多 >