Python 如何对数据帧中的索引值进行舍入
我想用名称results对pandas数据帧的索引值进行四舍五入,这样它们就没有任何十进制值。我使用从这里获取的以下代码。因此,基本上我有一个名为“set_timeslot”的列,我希望对其值进行四舍五入,然后将其用作索引Python 如何对数据帧中的索引值进行舍入,python,pandas,Python,Pandas,我想用名称results对pandas数据帧的索引值进行四舍五入,这样它们就没有任何十进制值。我使用从这里获取的以下代码。因此,基本上我有一个名为“set_timeslot”的列,我希望对其值进行四舍五入,然后将其用作索引 cols = ['set_timeslots'] results[cols]= results [cols].round(0) results.set_index('set_timeslots', inplace=True) 但是,正如您在屏幕截图中看到的,我仍然得到一个十
cols = ['set_timeslots']
results[cols]= results [cols].round(0)
results.set_index('set_timeslots', inplace=True)
但是,正如您在屏幕截图中看到的,我仍然得到一个十进制值
你知道我要做什么才能去掉十进制值吗?非常感谢您的评论。如果需要舍入并转换为整数,请添加:
在这种情况下,我们不能使用
pandas.DataFrame.round()
,因为round
模块用于decimal
点的trimming
。让我们只看我们的案例
# Import all-Important Libraries
import pandas as pd
# Reproduced Sample 'set_timeslots'
results = pd.DataFrame({
'set_timeslots':[1.0, 2.0, 3.0, 4.0, 5.0]
})
# Declaration of 'cols' variable for storing 'set_timeslots' column
cols = ['set_timeslots']
# Print result
results[cols]
适当的解决办法:-
因此,对于set\u时隙
从decimal
到int
的转换,我们可以使用pandas.DataFrame.astype()
模块
code
上述场景的说明如下:-
# Implementation of 'astype(int)' function
results[cols] = results[cols].astype(int)
# Print result after the Conversion
results
如您所见,我们已经实现了所需的输出
,即从set\u时隙
列
中删除十进制
点。希望这个解决方案
能帮助您澄清round()
函数和astype()
函数
要了解有关熊猫.DataFrame.round()的详细信息,请执行以下操作:-
要了解有关熊猫.DataFrame.astype()的详细信息,请执行以下操作:
嗯,这和我的回答不一样,更像是1小时前的回答?
# Output of above cell:-
set_timeslots
0 1.0
1 2.0
2 3.0
3 4.0
4 5.0
# Implementation of 'round' module:-
results[cols] = results[cols].round(0)
# Print result after round function
results
# Output of above cell:-
set_timeslots
0 1.0
1 2.0
2 3.0
3 4.0
4 5.0
# Implementation of 'astype(int)' function
results[cols] = results[cols].astype(int)
# Print result after the Conversion
results
# Output of above cell:-
set_timeslots
0 1
1 2
2 3
3 4
4 5