Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

select the first N elements of each row in a column

Tags:

python

pandas

I am looking to select the first two elements of each row in column a and column b.

Here is an example

df = pd.DataFrame({'a': ['A123', 'A567','A100'], 'b': ['A156', 'A266666','A35555']})

>>> df
      a        b
0  A123     A156
1  A567  A266666
2  A100   A35555

desired output

>>> df
      a      b
0     A1     A1
1     A5     A2
2     A1     A3

I have been trying to use df.loc but not been successful.

like image 580
SBad Avatar asked Oct 20 '25 04:10

SBad


2 Answers

Use

In [905]: df.apply(lambda x: x.str[:2])
Out[905]:
    a   b
0  A1  A1
1  A5  A2
2  A1  A3

Or,

In [908]: df.applymap(lambda x: x[:2])
Out[908]:
    a   b
0  A1  A1
1  A5  A2
2  A1  A3
like image 79
Zero Avatar answered Oct 21 '25 18:10

Zero


In [107]: df.apply(lambda c: c.str.slice(stop=2))
Out[107]:
    a   b
0  A1  A1
1  A5  A2
2  A1  A3
like image 28
MaxU - stop WAR against UA Avatar answered Oct 21 '25 17:10

MaxU - stop WAR against UA



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!