1

I have the pandas dataframe as below. I only want to dataframe that contains -P to _p(lowe case after that) and '-' remove and change the string after that with lower case.

>>> data= ['AAP','AAPL','BRK-A','AAIC-PB','AAP-C','YAB-PP']
>>> a = pd.DataFrame(data,columns=['code'])
>>> a
      code
0      AAP
1     AAPL
2    BRK-A
3  AAIC-PB
4    AAP-C
5   YAB-PP
>>> a['code']=a['code'].str.replace('-P','_p')
>>> a
>>> a
      code
0      AAP
1     AAPL
2    BRK-A
3  AAIC_pB
4    AAP-C
5   YAB_pP
>>> a['code']=a['code'].str.replace('-','')
>>> a
      code
0      AAP
1     AAPL
2     BRKA
3  AAIC_pB
4     AAPC
5   YAB_pP
>>> 

The desired output is

      code
0      AAP
1     AAPL
2    BRKa
3  AAIC_pb
4    AAPc
5   YAB_pp
2
  • Please explain why BRK-A becomes BRKa, but YAB-PP becomes YAB_pp Commented Dec 20, 2020 at 9:51
  • It is a pattern for code conversion. If contains '-', remove it and convert the string after tat with lowercase. If contains '-P', convert to _pand string after that convert to lower case. Commented Dec 20, 2020 at 9:55

1 Answer 1

2

You could do:

import pandas as pd

data= ['AAP','AAPL','BRK-A','AAIC-PB','AAP-C','YAB-PP']
a = pd.DataFrame(data,columns=['code'])


a['code'] = a['code'].str.replace('-(P.*)', lambda x: f'_{x.group(1).lower()}')
a['code'] = a['code'].str.replace('-(\w.*)', lambda x: x.group(1).lower())
print(a)

Output

      code
0      AAP
1     AAPL
2     BRKa
3  AAIC_pb
4     AAPc
5   YAB_pp

UPDATE

In versions previous to Python 3.6:

a['code'] = a['code'].str.replace('-(P.*)', lambda x: '_{}'.format(x.group(1).lower()))
a['code'] = a['code'].str.replace('-(\w.*)', lambda x: x.group(1).lower())
print(a)
Sign up to request clarification or add additional context in comments.

3 Comments

a['code'] = a['code'].str.replace('-(P.*)', lambda x: f'_{x.group(1).lower()}') return SyntaxError: invalid syntax
@bkcollection What Python version are you using?
I am using Python 2.7

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.