Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/303.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 熊猫:将列从分钟(类型对象)转换为数字_Python_Pandas - Fatal编程技术网

Python 熊猫:将列从分钟(类型对象)转换为数字

Python 熊猫:将列从分钟(类型对象)转换为数字,python,pandas,Python,Pandas,我想将数据帧的一列从一个对象转换为一个数字,例如float64。数据帧如下所示: import pandas as pd import numpy as np import datetime as dt df = pd.read_csv('data.csv') df ID MIN 0 201167 32:59:00 1 203124 14:23 2 101179 8:37 3 200780 5:22 4 202699 NaN

我想将数据帧的一列从一个对象转换为一个数字,例如float64。数据帧如下所示:

import pandas as pd
import numpy as np
import datetime as dt

df = pd.read_csv('data.csv')
df
   ID       MIN
0  201167  32:59:00
1  203124     14:23
2  101179      8:37
3  200780      5:22
4  202699       NaN
5  203117       NaN
6  202331  36:05:00
7    2561  30:43:00
我想将MIN列从type object转换为数字,例如float64。例如,32:59:00应变为32.983333

我不确定是否需要作为初始步骤,但我可以通过以下方式将每个NaN转换为0:


如何有效地转换整个列?我尝试了dt.datetime.strptime、df['MIN'].astype'datetime64'和pd.to_datetimedf['MIN']的变体,但没有成功。

定义转换器函数:

def str_to_number(time_str):
    if not isinstance(time_str, str):
        return 0
    minutes, sec, *_ = [int(x) for x in time_str.split(':')]
    return minutes + sec / 60
并将其应用于Min列:

工作

之前:

   ID   MIN
0   1   32:59:00
1   2   NaN
2   3   14:23
之后:

   ID   MIN
0   1   32.983333
1   2   0.000000
2   3   14.383333
以上是针对Python3的。这适用于Python 2:

def str_to_number(time_str):
    if not isinstance(time_str, str):
        return 0
    entries = [int(x) for x in time_str.split(':')]
    minutes = entries[0]
    sec = entries[1]
    return minutes + sec / 60.0

请注意60.0。或者,使用from uuu future uuuuu import print u函数来避免整数除法问题。

我通过Mac OS X上的Python 2.7.6在iPython笔记本中运行,转换器函数中的*u会导致语法错误:SyntaxError:无效语法。“我怎样才能避开这个问题?”亚当为Python 2添加了一个版本。
   ID   MIN
0   1   32.983333
1   2   0.000000
2   3   14.383333
def str_to_number(time_str):
    if not isinstance(time_str, str):
        return 0
    entries = [int(x) for x in time_str.split(':')]
    minutes = entries[0]
    sec = entries[1]
    return minutes + sec / 60.0