根据df2中相应的列对df1中的每一列进行舍入



df1:

BeScMn-0.19210.57290.11210.51960.0981>td>0.014
LiVCr
20.1564 -0.00110.0343
19.2871 -0.0027 0.0076 0.066
0.8693 0.0016 0.1997 0.0317 0.0533

您可以使用decimal模块中的Decimal来获取指数部分,并使用带有映射dict的.round来转换所有列:

from decimal import Decimal
exponent = lambda x: abs(Decimal(str(x)).as_tuple().exponent)
rounding = df2.T.squeeze().map(exponent)
out = df1.round(rounding)

输出:

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

注意:正如@mozway建议的那样,0.050只有2位小数,而不是3位小数,因为python不在乎尾随零。

这不是将数据转换为所需形式的标准方法,但它可能会解决您的目的。

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

最新更新