Python在整个熊猫数据框中的字符串中替换多个字符

时间:2019-03-26 07:32:32

标签: python-2.7

我试图用下划线('_')替换整个数据帧的字符串中的多个字符
数据框:

    Col1   Col2  b            
0    a b    a b  3       
1    b.1    b.1  4   
2    a+b    a+b  5   
3  a - b  a - b  6   
4    a-b    a-b  7      

我需要替换

 ' ' --->  '_'        (whitespace to underscore)   
 ' - '  ---> '___'    (three unserscores)   
 +,-,/,*,% --->   '_'  (all the chars to underscores)

我正在使用python 2.7和pandas 0.22.0

我尝试了不同的方法来实现这一目标,但是值没有得到更新,

可以逐列替换,但是无论列数如何,我都需要替换整个数据帧

df.replace({'Col1': {' ': '_', '.': '_','-':'_'}}, regex=True)

    df1 = df['A'].str.replace([' ','-','+'], ['_','_','_'],regex=True)     

预期输出

    Col1   Col2  b            
0    a_b    a_b  3       
1    b_1    b_1  4   
2    a_b    a_b  5   
3  a___b  a___b  6   
4    a_b    a_b  7

0 个答案:

没有答案