如何将列表列表中的数据舍入到2位小数?

时间:2017-10-03 15:23:55

标签: python arrays numpy

我有清单:

 A= [[85.71428570204081, 86.6666666608889, 71.11111110953087, 66.66666666349205], [39.999999996, 67.99999999728, 86.36363635971074, 72.72727272396693], [87.49999999635418, 83.33333333101852, 64.86486486311178, 66.66666666349205], [73.07692307411241, 90.47619047188209]]

所以我的预期结果是

A= [[85.71, 86.67, 71.11, 66.67], [40.00, 68.00, 86.36, 72.72], [87.50, 83.33, 64.86, 66.67], [73.08, 90.48]]

所以当我应用这段代码时:

 A=np.round(A,2)

它给我这个错误:

can't multiply sequence by non-int of type 'float'

任何人都可以给我一些提示吗?

2 个答案:

答案 0 :(得分:0)

IIUC:

In [114]: df = pd.DataFrame(A)

In [115]: df
Out[115]:
           0          1          2          3
0  85.714286  86.666667  71.111111  66.666667
1  40.000000  68.000000  86.363636  72.727273
2  87.500000  83.333333  64.864865  66.666667
3  73.076923  90.476190  64.285714  66.666667

In [116]: df.round(2)
Out[116]:
       0      1      2      3
0  85.71  86.67  71.11  66.67
1  40.00  68.00  86.36  72.73
2  87.50  83.33  64.86  66.67
3  73.08  90.48  64.29  66.67

答案 1 :(得分:0)

问题是你有一个列表列表,你必须为numpy方法提供np.round数组或矩阵。

您可以先将列表转换为,然后按照您的假装使用该方法

A= [[85.71428570204081, 86.6666666608889, 71.11111110953087, 66.66666666349205], [39.999999996, 67.99999999728, 86.36363635971074, 72.72727272396693], [87.49999999635418, 83.33333333101852, 64.86486486311178, 66.66666666349205], [73.07692307411241, 90.47619047188209]]
result =[]
for element in A:
    tmp = np.round(np.asarray(element),2)
    result.append(tmp.tolist())
result

[[85.71, 86.67, 71.11, 66.67],
 [40.0, 68.0, 86.36, 72.73],
 [87.5, 83.33, 64.86, 66.67],
 [73.08, 90.48]]