Mari
Mari

Reputation: 698

Add decimal point after two digits from left in pandas df columns

I have a df like below with int dtype. I want to Add decimal point after two digits from left for each value in pandas df columns

My Df

Descrip     a         b
VP3         52366599  10718233
VP3         522842650 106751
.
.
VP4         5232937   10542931
VP5         522842650 10615982
.
.

Requirement

I want my Df to be like

Descrip     a         b
VP3         52.366599  10.718233
VP3         52.2842650 10.6751
.
.
VP4         52.32937   10.542931
VP5         52.2842650 10.615982
.
.

Since values inside the dataframe doesn't have same number of digits, so i cannot able to process the easy way by dividing each number by 10e(something)

I hope there will be an easy method to solve this issue in pandas

Upvotes: 0

Views: 4430

Answers (4)

mportes
mportes

Reputation: 1837

I don't know pandas, but you could use the adjusted method in decimal module for a solution without str.

import decimal

for x in [52366599, 10718233,
          522842650, 106751,
          5232937, 10542931,
          522842650, 10615982]:

    shift = decimal.Decimal(x).adjusted() - 1

    print(x / 10**shift)

Output:

52.366599
10.718233
52.284265
10.6751
52.32937
10.542931
52.284265
10.615982

Upvotes: 3

Josh Friedlander
Josh Friedlander

Reputation: 11657

It might be quicker to do float division, just using string length:

df['a'] = df['a'].apply(lambda x: x / 10 ** (len((str(x))) - 2))

Or to do the whole dataframe:

df.applymap(lambda x: x / 10 ** (len((str(x))) - 2))

Upvotes: 2

hossein hayati
hossein hayati

Reputation: 1158

if i got your question carrectly, you can just convert each number to string and then add the point or comma at each index you wish to :

num = "1112334254"
new_num = num[:2] +'.'+ num[2:]
print(new_num)

the output should be something like this:

11.12334254

Upvotes: 2

Chris
Chris

Reputation: 29742

You can iterate columns with str and insert . at desired position:

df = pd.DataFrame(np.random.randint(0, 2000, (5, 2)))
print(df)
      0     1
0    97   148
1   796   935
2  1992   594
3  1498   416
4    34  1289

df = df.astype(str)
for c in df:
    df[c] = (df[c].str[:2] + '.' + df[c].str[2:]).astype(float)
print(df)
       0      1
0  97.00  14.80
1  79.60  93.50
2  19.92  59.40
3  14.98  41.60
4  34.00  12.89

Upvotes: 5

Related Questions