python-3.x - 使用 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
解决方案
我想你需要这个
这是您的示例时间
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
推荐阅读
- react-native - 如何使用 Expo 清理(重置缓存)React Native。不知道是不是缓存问题
- python-3.x - 从存储在不同位置的另一个 python 脚本执行(包括打印字符串等)python 脚本
- php - 更改发件人电子邮件地址
- c# - 如何使泛型类实现接口
- puppet - 在 puppet 中选择一个具有给定键值对的嵌套哈希
- hyperledger-composer - 使用超级账本作曲家启动业务网络时出错
- sql - 将一列中的字符串拆分为表维护 ID 的多个分隔符
- php - 与 laravel-datatable 中的排序和分页功能冲突
- c# - 创建一个接受具有返回类型的函数的动作
- python - Plotly 和袖扣在 Anaconda 中不起作用