How to insert string value into specific column value on python pandas?

Viewed 5245

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
3 Answers

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

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

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
Related