如何从浮点数中取前一位或两位数?

时间:2018-10-10 16:49:32

标签: python pandas dataframe

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

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

1000.0 -> 10
901.0 ->  9

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

1850.0 -> 18
2301.0 -> 23

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

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])

3 个答案:

答案 0 :(得分:0)

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

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

答案 1 :(得分:0)

使用楼层划分和int强制转换怎么办?

>>> int(1000.0 // 100)
10
>>> int(901.0 // 100)
9
>>> int(1850.0 // 100)
18
>>> int(2301.0 // 100)
23

答案 2 :(得分:0)

我想这里最简单的选择是使用“取模”(%)函数:

List[_]

一个更好的选择是使用datetime库来定义时间并以此为基础(这里是文档的链接:https://docs.python.org/2/library/datetime.html