如何从浮点数中取前一位或两位数? [英] How to take first one or two digits from float number?

查看:129
本文介绍了如何从浮点数中取前一位或两位数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Pandas数据框.在一个系列中,我将小时和分钟的时间表示为float,如下所示.我只想要几个小时:

I have a Pandas dataframe. In a series, I have time in hour and minute represented as float, as below. I want only the hours:

时间列值从(1到12)的示例:

1000.0 -> 10
901.0 ->  9

时间列值从(13到24)的示例:

1850.0 -> 18
2301.0 -> 23

我已经尝试过这段代码,但是直到关闭编辑器才花费很长时间,所以我看不到结果

I have tried this code but it takes very long time until I close the editor so I didn't see the result

for index,row in df.iterrows():
    if(row['time']<=959.0):
        row['hour']= int(str(row['dep_time'])[:1])
    elif row['dep_time']>959.0: 
         row['dep_hour']=int(str(row['dep_time'])[:2])

推荐答案

对于Pandas,在向量化方法可用时不要迭代行.在这种情况下,您可以使用下限分割,后跟 pd.Series.astype :

With Pandas, don't iterate rows when vectorised methods are available. In this case, you can use floor division followed by pd.Series.astype:

df['hour'] = (df['dep_time'] // 100).astype(int)

这篇关于如何从浮点数中取前一位或两位数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆