sergiomahi
sergiomahi

Reputation: 992

Add a character in a string inside a column dataframe

I have a dataframe with some numbers (or strings, it doesn't actually matter). The thing is that I need to add a character in the middle of them. The dataframe looks like this (I got it from Google Takeout)

 id       A         B
  1    512343    -1234
  1    213       1231345
  1    18379     187623 

And I want to add a comma in the second position

  id      A             B
   1    51,2343    -12,34
   1    21,3        12,31345
   1    18,379      18,7623 

A and B are actually longitude and latitude so I think it is not possible to achieve to add the comma in the right place since there is no way to know if a number is supposed to have one or two digits as coordinates, but it would do the trick if I can put the comma on the second position.

Upvotes: 0

Views: 1493

Answers (3)

Georgina Skibinski
Georgina Skibinski

Reputation: 13377

This should do the trick:

df[["A", "B"]]=df[["A", "B"]].astype(str).replace(r"(\d{2})(\d+)", r"\1,\2", regex=True)

Outputs:

   id        A         B
0   1  51,2343    -12,34
1   1     21,3  12,31345
2   1   18,379   18,7623

Upvotes: 2

Quang Hoang
Quang Hoang

Reputation: 150725

Here's another approach with str.extract:

for c in ['A','B']:
    df[c] = df[c].astype(str).str.extract('(-?\d{2})(\d*)').agg(','.join,axis=1)

Output:

   id        A         B
0   1  51,2343    -12,34
1   1     21,3  12,31345
2   1   18,379   18,7623

Upvotes: 1

Sajan
Sajan

Reputation: 1267

You could do something like this -

import numpy as np
df['A'] = np.where(df['A']>=0,'', '-') + ( df['A'].abs().astype(str).str[:2] + ',' + df['A'].abs().astype(str).str[2:] )
df['B'] = np.where(df['B']>=0,'', '-') + ( df['B'].abs().astype(str).str[:2] + ',' + df['B'].abs().astype(str).str[2:] )
df
   id        A         B
0   1  51,2343    -12,34
1   1     21,3  12,31345
2   1   18,379   18,7623

Upvotes: 0

Related Questions