熊猫数据框中的字符串列操作

Alp*_*lph 3 python regex string pandas

我在这样的数据框中有一个字符串列(时间)。我想在数字之间加下划线并删除月份。

Time
2- 3 months          
1- 2 months          
10-11 months          
4- 5 months
 Desired output:
2_3           
1_2           
10_11           
4_5 
Run Code Online (Sandbox Code Playgroud)

这是我正在尝试的方法,但似乎没有用。

def func(string):
    a_new_string =string.replace('- ','_')
    a_new_string1 =a_new_string.replace('-','_')
    a_new_string2= a_new_string1.rstrip(' months')
    return a_new_string2
Run Code Online (Sandbox Code Playgroud)

并将功能应用于数据框。

df['Time'].apply(func)
Run Code Online (Sandbox Code Playgroud)

EdC*_*ica 6

一种选择是使用3个str replace呼叫:

In [18]:

df['Time'] = df['Time'].str.replace('- ', '_')
df['Time'] = df['Time'].str.replace('-', '_')
df['Time'] = df['Time'].str.replace(' months', '')
df
Out[18]:
    Time
0    2_3
1    1_2
2  10_11
3    4_5
Run Code Online (Sandbox Code Playgroud)

我认为您的问题可能是您没有分配apply背部的结果:

In [21]:

def func(string):
    a_new_string =string.replace('- ','_')
    a_new_string1 =a_new_string.replace('-','_')
    a_new_string2= a_new_string1.rstrip(' months')
    return a_new_string2

df['Time'] = df['Time'].apply(func)
df
Out[21]:
    Time
0    2_3
1    1_2
2  10_11
3    4_5
Run Code Online (Sandbox Code Playgroud)

您也可以将其设置为一体式:

In [25]:

def func(string):
    return string.replace('- ','_').replace('-','_').rstrip(' months')

df['Time'] = df['Time'].apply(func)
df
Out[25]:
    Time
0    2_3
1    1_2
2  10_11
3    4_5
Run Code Online (Sandbox Code Playgroud)