python - 如何通过优雅的编码更快地将一些逻辑应用于数据框列
问题描述
我正在阅读一个包含许多列的 csv 文件,其中之一是 TOD(一天中的时间)。有些事件会在午夜过后,而不是回滚到 00:00,时间只会在 24:00 之后不断增加。例如 23:59:50, 24:00:01, 24:00:10,...) EntryTOD 被解析为字符串。
我想应用一个简单的逻辑,即时间大于 24,只需减去 24 小时。这是我的代码:
for row in f2.itertuples():
# Fix times > 24h
if int(row.EntryTOD[0:2]) >= 24:
actualTime = int(row.EntryTOD[0:2]) - 24
f2.EntryTOD[row.Index-1] = str(actualTime) + row.EntryTOD[2:]
此代码有效,但对于 80k+ 行来说有点慢。运行大约需要 30-40 秒。
我的问题是:
1)有没有更快的方法来做到这一点?
2)另外,由于我对 Python 不是很好,有没有更优雅的方法?它可能仍然涉及遍历整个列,但我觉得这可以在 1 行代码中完成
先感谢您,
圭多
解决方案:感谢 Rene:
f2.EntryTOD = f2.EntryTOD.apply(lambda x: str(int(x.split(':')[0])-24)+x[2:] if int(x.split(':')[0]) > 23 else x)
这是非常快的单班轮!
解决方案
我认为这就是你要找的:
# Sample df
data = [
['25:22:22', 1, 5],
['01:01:01', 36, 2]
]
cols = ['EntryTOD', 'two', 'three']
df = pd.DataFrame(data, columns = cols)
df
EntryTOD two three
0 25:22:22 1 5
1 01:01:01 36 2
解决方案:
df['hour'] = (df['EntryTOD'].str[0:2]).astype(int)
df.loc[
df.hour >= 24, 'hour'
] = df.loc[df.hour >= 24, 'hour'] - 24
# Edit EntryTOD variable
for i in range(df.shape[0]):
df.EntryTOD.iloc[i] = df.EntryTOD.iloc[i].replace(
df['EntryTOD'].str[0:2].iloc[i], '0'+df['hour'].astype(str).iloc[i]
)
输出:
EntryTOD two three hour
0 01:22:22 1 5 1
1 01:01:01 36 2 1
推荐阅读
- mongodb - 如何在 Mongo DB 中获取此父子查询数据
- python - Kivy - 标签文本堆栈,直到调整窗口大小
- asp.net-mvc - 无法在干净的 autofac.mv5 安装上加载文件或程序集 System.Runtime.CompilerServices.Unsafe
- c - C:输出解析两次时如何避免重复popen?
- reactjs - 如何在客户网站上标记 React 应用程序?
- typescript - 如何使用 graphql-tools 从两个源位置加载 GraphQL 模式?
- php - localstack s3 无法从 php 访问
- python-3.x - 将一个函数的多个返回值作为参数传递给另一个函数
- bash - 通过 Bitrise 运行时,Bash shell 脚本命令乱序执行
- java - 虽然使用相同的数据提供者在 2 个不同的类中有 2 个测试用例,但在执行第 2 个用例时,超类中的所有值都会重置为 null