Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split string in a column based on character position

Tags:

python

pandas

I have a dataframe like this:

                Basic Stats        Min       Max      Mean     Stdev   
1        LT50300282010256PAC01   0.336438  0.743478  0.592622  0.052544   
2        LT50300282009269PAC01   0.313259  0.678561  0.525667  0.048047   
3        LT50300282008253PAC01   0.374522  0.746828  0.583513  0.055989   
4        LT50300282007237PAC01  -0.000000  0.749325  0.330068  0.314351   
5        LT50300282006205PAC01  -0.000000  0.819288  0.600136  0.170060 

and for the column Basic Stats I want to retain only the characters between [9:12] so for row 1 I only want to retain 2010 and for row 2 I only want to retain 2009. Is there a way to do this?

like image 546
Stefano Potter Avatar asked Dec 08 '22 01:12

Stefano Potter


1 Answers

Just use vectorised str method to slice your strings:

In [23]:

df['Basic Stats'].str[9:13]
Out[23]:
0    2010
1    2009
2    2008
3    2007
4    2006
Name: Basic Stats, dtype: object
like image 61
EdChum Avatar answered Jan 09 '23 15:01

EdChum