首页 > 解决方案 > 打印具有最大小数点的列的值

问题描述

这是我的数据框:

     col1       col2
0    12.13      13.13
1    100.133    12.19994
2    11.16664   140.13
3    9.13       2.13
4    3.23       10.13

现在我想要具有最大小数点长度的列值。

**OUTPUT:**
     maximum_de_point
**COL1** 11.16664
**COL2** 12.19994

标签: pythonpandasdataframemaxprecision

解决方案


一种选择是用 拆分值str.split,取str.len小数部分的 并找到idxmax每列的 。然后lookup使用结果值:

df_ixmax = df.astype(str).apply(lambda x: x.str.split('.').str[1].str.len()).idxmax(0)
df_ixmax[:] =df.lookup(*df_ixmax.reset_index().values[:,::-1].T)

df_ixmax
col1    11.16664
col2    12.19994
dtype: float64

或者我们也可以使用decimal.Decimal,它可以通过返回的命名元组 by 获得小数位数as_tuple(),然后从结果中类似上面的索引数据帧:

from decimal import Decimal 

ix = [[Decimal(str(x)).as_tuple().exponent for x in col] for col in df.values.T]
max_vals = df.values[np.array(ix).argmin(1), np.arange(df.shape[1])]
pd.Series(max_vals, index=df.columns)

col1    11.16664
col2    12.19994
dtype: float64

推荐阅读