Skip to main content
 首页 » 编程设计

python之列上的 Multiindiex str 替换

2024年11月01日10Terrylee

我想替换多索引数据框中列中的所有值,我发现了一种肮脏的方法,但我正在寻找更清洁的方法

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

所有数字都是字符串,所以我需要将它们转换为 float 或整数,因此需要 str.replace 函数

示例数据框

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) 

这行得通,但我不想对每一列都这样做

我一直在尝试着玩

df.loc[:,pd.IndexSlice[:,'B']].str.replace('%','').astype( float )

但是我得到了错误

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

我试过

df.loc[:,pd.IndexSlice[:,'Percent']].replace('%','')

它返回没有错误的数据框,但不对它做任何事情

如果我这样做

df.loc[:,pd.IndexSlice[:,'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

请您参考如下方法:

您可以尝试 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和update返回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