df1:
Li | BeScV | Cr | Mn||
---|---|---|---|---|
20.1564 | -0.0011 | -0.19210.0343 | 0.57290.1121||
19.2871 | -0.0027 | 0.0076 | 0.066 | 0.51960.0981|
0.8693 | 0.0016 | 0.1997 | 0.0317 | 0.0533 | >td>0.014
您可以使用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]))