pandas中数据框中的字符串列操作

时间:2015-03-16 16:06:12

标签: python regex string pandas

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

Time
2- 3 months          
1- 2 months          
10-11 months          
4- 5 months
 Desired output:
2_3           
1_2           
10_11           
4_5 

这是我正在尝试的但似乎不起作用。

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'].apply(func)

1 个答案:

答案 0 :(得分:4)

一种选择是使用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

我认为您的问题可能是因为您没有将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

你也可以把这个作为一个班轮:

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