代码之家  ›  专栏  ›  技术社区  ›  Ausghostdog

柱上的多索引str替换

  •  0
  • Ausghostdog  · 技术社区  · 5 年前

    我想替换多索引数据帧中一列中的所有值,我找到了一种肮脏的方法,但我正在寻找更干净的方法

    如果有帮助的话,可以从.xlsx导入数据,因为它可以使用千位运算符从第一列中删除“,”。

    所有数字都是字符串,所以我需要将它们转换为浮点或整数,因此结构更换功能

    示例数据帧

    Name    0                       1                      ...
    Col     A           B           A            B         ...
    0       409511  30.3%           355529   30.3%  ...
    1       332276  20.3%           083684   20.3%  ...
    2       138159  10.3%           570834   10.3%  ...
    

    如果我使用

    df['0','B']= df['0','B'].str.replace('%','').astype(float)
    

    这是可行的,但我不想对每一个专栏都这样做

    我一直想和你玩

    航向位置[:,pd索引[:,'B']]。结构更换('%','').astype(浮点)

    但我发现了错误

    “DataFrame”对象没有属性“str”

    航向位置[:,pd索引[:,'Percent']].替换('%','')

    它无错误地返回数据帧,但对其不做任何操作

    如果我这么做

    航向位置[:,pd索引[:,'Percent']].replace('%','').astype(float)

    无法将字符串转换为float:“33.3%”

    https://pandas.pydata.org/pandas-docs/stable/user_guide/advanced.html 但是没有替代品

    我也找不到任何东西 https://jakevdp.github.io/PythonDataScienceHandbook/03.05-hierarchical-indexing.html

    0 回复  |  直到 5 年前
        1
  •  1
  •   Andy L.    5 年前

    你可以试试 Index.Slice loc ,和 update 注意 : 你需要 regex=True )

    idx = pd.IndexSlice
    df.update(df.loc[:, idx[:,'B']].replace('%', '', regex=True).astype(float))
    
    Out[1374]:
            0             1
            A     B       A     B
    0  409511  30.3  355529  30.3
    1  332276  20.3   83684  20.3
    2  138159  10.3  570834  10.3
    

    或使用 filter 更新 df

    df.update(df.filter(like='B').replace('%', '', regex=True).astype(float))
    
    Out[1363]:
            0             1
            A     B       A     B
    0  409511  30.3  355529  30.3
    1  332276  20.3   83684  20.3
    2  138159  10.3  570834  10.3