我在这样的数据帧中有一个字符串列(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)发布于 2015-03-16 16:09:09
一种选择是使用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_5https://stackoverflow.com/questions/29081530
复制相似问题