【发布时间】:2015-05-18 20:16:51
【问题描述】:
我在这样的数据框中有一个字符串列(时间)。我想在数字之间加上下划线并删除月份。
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)
【问题讨论】:
-
您是否将结果分配回去?
df['Time'] = df['Time'].apply(func)? -
是的。我想在数据框的时间列中应用该函数。
标签: python regex string pandas