首页 > 解决方案 > 使用 panda 将整列中的时间转换为从 csv 导入的浮点数

问题描述

在我的 csv 文件中,我有包含三个数据列的时间列。我需要使用熊猫将时间转换为浮点数。但它给了我一个错误,invalid literal for int() with base 10: 'g' 你能建议我解决这个错误吗?我的代码是,

def time_to_float(t):
    """ convert "hh:mm:ss" to float (0, 1) only of the correct format """
    if t == '-':
        return None
    a = [int(i) for i in t.split(":")]
    if len(a) == 3:
        return round((a[0] + a[1] / 60 + a[2] / 3600) / 24, 5)
    else:
        return t


def pick_column(data_, n, start=1):
    """ pick all the n'th column data starting from "start" """
    return [time_to_float(data_[i][n]) for i in range(start, len(data_))]

data = pd.read_csv('data4.csv')
data = [i for i in data]


Time = pick_column(data, 0)
g = pick_column(data, 1)
p = pick_column(data, 2)
c = pick_column(data, 3)
y = pick_column(data, 4)



print(Time)
print(g)
print(p)
print(c)
print(y)

我的数据集是

Time	   g	 p	  c	 y
0:06:15	141	NaN	NaN	141
0:08:00	NaN	10	NaN	117
0:09:00	NaN	15	NaN	103
0:09:25	95	NaN	NaN	95
0:09:30	NaN	NaN	50	93

标签: python-3.xpandasjupyter-notebook

解决方案


我想你需要这个

这是您的示例时间

print(df['Time'])
1:06:15

要将其转换为每天的秒数,您可以这样做

df['TimeFloat'] = (pd.DatetimeIndex(df['Time']).astype(np.int64)/10**9)%86400

使用 86400 的模数,因为一天有 86400 秒您可以根据您的转换(秒、分钟、毫秒)修改模数值此外,如果您需要在 中进行转换int,您可以简单地使用//而不是/

最终的 df 将是这个

   Time  TimeFloat
1:06:15     3975.0

推荐阅读