Home > Mobile >  pandas convert object to decimal(3,9)
pandas convert object to decimal(3,9)

Time:06-23

I've got a dataframe with column filled with a dtype: object. These values are retrieved from an asci file (position x length y).

0       001191833837
1       001083340239
2       000716901420
3       001191833837
4       001191833837
            ...     
4162    001160715789
4163    001160715789
4164    001160715789
4165    000875149515
4166    001160715789
Name: WEGING, Length: 4167, dtype: object

These values should be interpreted as a number with 9 decimal places (like decimal(3,9)). How do I convert the dtype object to the desired result?

0       001.191833837
1       001.083340239
2       000.716901420
3       001.191833837
4       001.191833837
            ...     
4162    001.160715789
4163    001.160715789
4164    001.160715789
4165    000.875149515
4166    001.160715789

TIA.

CodePudding user response:

If you want a float, use:

df['WEGING2'] = pd.to_numeric(df['WEGING']).div(10**9)

For a string:

df['WEGING3'] = df['WEGING'].str.replace(r'^(.{3})', r'\1.', regex=True)

output:

         WEGING   WEGING2        WEGING3
0  001191833837  1.191834  001.191833837
1  001083340239  1.083340  001.083340239
2  000716901420  0.716901  000.716901420
3  001191833837  1.191834  001.191833837
4  001191833837  1.191834  001.191833837
  • Related