使用Pandas基于另一列进行舍入

时间:2017-10-27 22:18:27

标签: python-3.x pandas

我有一个数据框,其中1列是值列表,另一列是我需要舍入的位数。它看起来像这样:

api 'com.google.dagger:dagger-android:2.11'

我正在寻找一个如下所示的输出:

  ValueToPlot  B_length
0       13.80       1.0
1       284.0       0.0
2         5.9       0.0
3        1.38       1.0
4       287.0       0.0

最后,我希望Rounded列采用字符串格式,因此最终结果为:

  ValueToPlot  B_length  Rounded
0       13.80       1.0     13.8
1       284.0       0.0      284
2         5.9       0.0        6
3        1.38       1.0      1.4
4       287.0       0.0      287

我曾尝试在Pandas中使用 ValueToPlot B_length Rounded 0 13.80 1.0 '13.8' 1 284.0 0.0 '284' 2 5.9 0.0 '6' 3 1.38 1.0 '1.4' 4 287.0 0.0 '287' 功能但未成功。如果可能的话,我宁愿避免循环。

2 个答案:

答案 0 :(得分:2)

使用链式format s
'{{:0.{}f}}'.format(3)评估为'{:0.3f}'。双'{{}}'告诉format转义'{}'。然后'{:0.3f}'.format(1)评估为1.000。我们可以通过链接来捕捉这个概念。

f = lambda x: '{{:0.{}f}}'.format(int(x[1])).format(x[0])

df.assign(Rounded=df.apply(f, 1))

   ValueToPlot  B_length Rounded
0        13.80       1.0    13.8
1       284.00       0.0     284
2         5.90       0.0       6
3         1.38       1.0     1.4
4       287.00       0.0     287

使用列名

更明确一点
f = lambda x: '{{:0.{}f}}'.format(int(x['B_length'])).format(x['ValueToPlot'])

df.assign(Rounded=df.apply(f, 1))

   ValueToPlot  B_length Rounded
0        13.80       1.0    13.8
1       284.00       0.0     284
2         5.90       0.0       6
3         1.38       1.0     1.4
4       287.00       0.0     287

我通常喜欢使用assign,因为它会生成一个附加了新列的数据框副本。我可以编辑原始数据框

f = lambda x: '{{:0.{}f}}'.format(int(x[1])).format(x[0])

df['Rounded'] = df.apply(f, 1)

或者我可以将assign与实际字典一起使用

f = lambda x: '{{:0.{}f}}'.format(int(x[1])).format(x[0])

df.assign(**{'Rounded': df.apply(f, 1)})

答案 1 :(得分:1)

有点长......但是工作

df.apply(lambda x : str(round(x['ValueToPlot'],int(x['B_length']))) if x['B_length']>0 else str(int(round(x['ValueToPlot'],int(x['B_length'])))),axis=1)
Out[1045]: 
0    13.8
1     284
2       6
3     1.4
4     287
dtype: object