I have string column (time) in a data frame like this, I put underscore between digits and want to remove months
Time 2 - 3 months 1 - 2 months 10-11 months 4 - 5 months desired product:. 2_3 1_2 10_11 4_5
What I'm trying here but does not seem to be working
DEF Function (string) :. A_new_string = string.replace ('-', '_') a_new_string1 = a_new_string.replace ('-', '_') a_new_string2 = a_new_string1.rstrip ('of the month) a_new_string2
Applying the function to frame more data
DF ['time']. (Func)
is an option 3 [code] str To change , call
:
In [18]: Use df ['time'] = df ['time']. ('-', '_') df ['time'] = df ['time']. Str.replace ('-', '_') df ['time'] = df ['time'] .str.replace ('month', '') df out [18]: time 0 2_3 1 1_2 2 10_11 3 4_5
I think your problem (you may specify the result of your apply
back:
) Are not: [21]: def func (string): a_new_string = string.replace ('-', '_') a_new_string1 = a_new_string.replace ('-.', '_') A_new_string2 = a_new_string1.rstrip ( 'Of the month) return a_new_string2 df [' time '] = df [' time '] apply (function) df outside [21]: time 0_3 2 1 1 2 2 10_11 3 4_5
Also one can do one liner:
in [25]: Def Maroh (string): .. in place of return string.replace ('-', '_') ('-', '_') rstrip ('of the month) df [' time '] = df [' time '] .apply (func) df out [25]: time 0 2_3 1 1_2 2 10_11 3 4_5
No comments:
Post a Comment