5

I have the following dataframe.

import pandas as pd
data=['ABC1','ABC2','ABC3','ABC4']
data = pd.DataFrame(data,columns=["Column A"])



    Column A
0   ABC1
1   ABC2
2   ABC3
3   ABC4

How to insert "-" a ABC on column A of data?

Output:

  Column A
0   ABC-1
1   ABC-2
2   ABC-3
3   ABC-4
2
  • 4
    Surely your actual problem can't be this straightforward... can you provide a more substantial minimal reproducible example that more accurately represents your data? The solution to this is str.replace with backreferences, but may not be so for your actual data. Commented Dec 17, 2018 at 16:33
  • i.e., replace(r'(ABC)', r'\1-') Commented Dec 17, 2018 at 16:35

3 Answers 3

4

A possible solution is

data['Column A'] = data['Column A'].str[:-1] + '-' + data['Column A'].str[-1]
print (data)
#  Column A
#0    ABC-1
#1    ABC-2
#2    ABC-3
#3    ABC-4
Sign up to request clarification or add additional context in comments.

Comments

3

The Simplest solution to Use replace method as a regex and inplace method to make it permanent in the dataframe.

>>> data['Column A'].replace(['ABC'], 'ABC-', regex=True, inplace=True)
print(data)
  Column A
0    ABC-1
1    ABC-2
2    ABC-3
3    ABC-4

1 Comment

I dont know why someone have downvoted the solution, any reason?
2

Here's a way which only assumes that the numbers to be preceded by a dash are at the end:

df['ColumnA'].str.split('([A-z]+)(\d+)').str.join('-').str.strip('-')

0    ABC-1
1    ABC-2
2    ABC-3
3    ABC-4

Another example:

df = pd.DataFrame({'ColumnA':['asf1','Ads2','A34']})

Will give:

df['ColumnA'].str.split('([A-z]+)(\d+)').str.join('-').str.strip('-')

0    asf-1
1    Ads-2
2     A-34

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.