python - 避免嵌套 .apply()

标签 python pandas datetime apply

我正在处理由同一天/日期的不同时间组成的数据集。不同的时间代表给定事件的发生。除了时间之外,日期也在另一列中给出(有关更多详细信息,请参见下面的数据片段)。

为了进一步的数据处理,我需要将不同的时间与日期结合起来以获得完整的日期时间戳。幸运的是,我能够通过像这样实现嵌套的 .apply() 调用来实现所需的输出:

import io

import pandas as pd


DATA_STRING = """
date        event_1     event_2     event_3  
2019-12-16  14:01:00    14:27:00    14:47:00
2020-01-16  13:47:00    14:08:00    14:28:00
2020-01-20  12:02:00    12:23:00    12:42:00
"""

TIME_COLUMNS = ['event_1', 'event_2', 'event_3']


def combine_timestamp(row):
    date = row['date']
    times = row[TIME_COLUMNS]
    return times.apply(lambda t: pd.Timestamp.combine(date, t.time()))


file_like = io.StringIO(DATA_STRING)
df = pd.read_csv(file_like, sep='\s+')

df['date'] = pd.to_datetime(df['date'])
df[TIME_COLUMNS] = df[TIME_COLUMNS].apply(pd.to_datetime)
# --> timestamps with date set to today (not a problem as time is relevant only)

df[TIME_COLUMNS] = df.apply(combine_timestamp, axis='columns')

print(df)

打印:

        date             event_1             event_2             event_3
0 2019-12-16 2019-12-16 14:01:00 2019-12-16 14:27:00 2019-12-16 14:47:00
1 2020-01-16 2020-01-16 13:47:00 2020-01-16 14:08:00 2020-01-16 14:28:00
2 2020-01-20 2020-01-20 12:02:00 2020-01-20 12:23:00 2020-01-20 12:42:00

但是,我想知道是否有更优雅的方法来实现它并避免这些嵌套的 .apply()` 调用。

最佳答案

我可以想到这样的事情:将带有事件列的日期添加为字符串,然后转换为日期时间:

df = pd.read_csv(file_like, sep='\s+')
out = df.assign(**(df['date'].add(' ').to_numpy()[:,None] + df.filter(like='event')))
out = out.apply(pd.to_datetime)

print(out)

         date             event_1             event_2             event_3
0  2019-12-16 2019-12-16 14:01:00 2019-12-16 14:27:00 2019-12-16 14:47:00
1  2020-01-16 2020-01-16 13:47:00 2020-01-16 14:08:00 2020-01-16 14:28:00
2  2020-01-20 2020-01-20 12:02:00 2020-01-20 12:23:00 2020-01-20 12:42:00

关于python - 避免嵌套 .apply(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67127681/

相关文章:

ruby on rails 递归子字符串

python - 难以使用 statsmodels Python 包设置图例

python - 网页抓取 : request not returning complete content of the webpage

python - 在 for 循环中构建不同的 networkx 图

Python Pandas,将字符串列导出到 Excel 文件中

datetime - 我需要一个转换函数,从整数到日期时间

Python C/C++ 包装器与纯 C/C++ 性能

python - Pandas:计算列中的一些值

python - Pandas 情节 : how to plot some columns of a dataframe with the same color but different style and some cols with different color and different style?

Python:从时间戳到日期时间