Home > Net >  Round each column in df1 based on corresponding column in df2
Round each column in df1 based on corresponding column in df2

Time:01-05

df1:

Li Be Sc V Cr Mn
20.1564 -0.0011 -0.1921 0.0343 0.5729 0.1121
19.2871 -0.0027 0.0076 0.066 0.5196 0.0981
0.8693 0.0016 0.1997 0.0317 0.0533 0.014

df2:

Li Be Sc V Cr Mn
2.0 0.050 0.3 0.111 0.50 0.40

I need to round the columns in df1 to the same number of decimals places as the corresponding columns in df2. The issue is that each df contains 40 columns all needing to be rounded to a specific number of decimal places.

I can do this column by column like

df1["Li"]=df1["Li"].round(1)
df1["Be"]=df1["Be"].round(3)
etc

Is there an easier way to round all the columns in df1 based on the number of decimals in df2

desired output:

Li Be Sc V Cr Mn
20.2 -0.001 -0.2 0.034 0.57 0.11
19.3 -0.003 0 0.066 0.52 0.1
0.9 0.002 0.2 0.032 0.05 0.01

CodePudding user response:

You can use Decimal from decimal module to get the exponent part and use .round with a mapping dict to convert all columns:

from decimal import Decimal

exponent = lambda x: abs(Decimal(str(x)).as_tuple().exponent)
rounding = df2.T.squeeze().map(exponent)

out = df1.round(rounding)

Output:

>>> out
     Li   Be   Sc      V   Cr   Mn
0  20.2 -0.0 -0.2  0.034  0.6  0.1
1  19.3 -0.0  0.0  0.066  0.5  0.1
2   0.9  0.0  0.2  0.032  0.1  0.0

>>> rounding
Li    1
Be    2
Sc    1
V     3
Cr    1
Mn    1
Name: 0, dtype: int64

Note: as @mozway suggested you, 0.050 has only 2 decimals not 3 because python doesn't care about trailing zeroes.

CodePudding user response:

This could not be a very standard way to convert data to the desired form but it might solve your purpose.

for i in df2.columns:
    a = str(df2[i][0])
    df1[i] = df1[i].round(len(a.split('.')[1]))
  • Related