python - Pandas 多索引将 float 更改为字符串

标签 python pandas

pd.__version__
'0.15.2'

我有一个具有三级多索引的 Pandas 数据框。当我连接两个数据帧时,它把最低的索引变成了一个 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

我也试过 set_levels,但不确定语法。

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

给我这个错误

TypeError: 'Index' object is not callable

最佳答案

如其他帖子中所述,重置索引、更改数据类型并设置新索引可能更容易。

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

总的来说,我发现操纵多索引(索引?)有时值得,有时则不值得。更改级别变得冗长。如果您致力于这项事业,那么这很有效:

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

关于python - Pandas 多索引将 float 更改为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58324817/

相关文章:

python - 值与一组值的矢量化比较

python - 如何检索 GAE 高复制数据存储中记录的最新版本?

python - 使用正则表达式提取电话号码,后面或前面没有数字

python - 如何按日期时间索引过滤 DataFrameGroupBy 对象

python - 将连续的相等值分组并累加

python - 使用 df1 中的值从 df2 中检索值,其中 df2 列和索引包含一系列值

python - Pandas - 根据其他列中的值将数据添加到列

python - 语法错误; Python游戏吐出super方法并导入

python - 尝试将 True/False 值返回到 python 中的定义时出错

python - 神经网络模型精度超低