按具有特定名称的列从秒切换到 Timedelta

Switch from seconds to Timedelta by column with specific name

让它成为以下python pandas数据框:

other value time_UK total_time_UK color counter_time_UK
392 idk 0 0 red 8393283
2393 odp 930233 23423423 blue 322332
392 kfl 0 0 red 0
323 bcn 783732 32423 green 42332
9695 uie 0 0 red 3423283
111 xas 0 3423323 blue 322

我希望包含字符串 time_UK 的列将其值(以秒为单位)转换为 TimeDelta,如果其值为 0 则转换为 NaT。

other value time_UK total_time_UK color counter_time_UK
392 idk NaT NaT red pd.to_timedelta(8393283)
2393 odp pd.to_timedelta(930233) pd.to_timedelta(23423423) blue pd.to_timedelta(322332)
392 kfl NaT NaT red NaT
323 bcn pd.to_timedelta(783732) pd.to_timedelta(32423) green pd.to_timedelta(42332)
9695 uie NaT NaT red pd.to_timedelta(3423283)
111 xas NaT pd.to_timedelta(3423323) blue pd.to_timedelta(322)

现在我正在使用下一个代码:

    # Sets the 0 second values to NaT    
    df.loc[df['time_UK'] == 0.0, 'time_UK'] = pd.NaT
    
    # Converts seconds to TimeDelta type
    df['time_UK'] = pd.to_timedelta(df['time_UK'], unit='s')

感谢您提供的帮助。

使用DataFrame.filter for DataFrame df1 by columns name time_UK, convert to floats, replace 0 by DataFrame.mask with convert all columns to timedeltas by to_timedelta:

df1 = df.filter(like='time_UK').astype(float)
df[df1.columns] = df1.mask(df1.eq(0)).apply(pd.to_timedelta, unit='s')
print (df)
   other value          time_UK     total_time_UK  color  counter_time_UK
0    392   idk              NaT               NaT    red 97 days 03:28:03
1   2393   odp 10 days 18:23:53 271 days 02:30:23   blue  3 days 17:32:12
2    392   kfl              NaT               NaT    red              NaT
3    323   bcn  9 days 01:42:12   0 days 09:00:23  green  0 days 11:45:32
4   9695   uie              NaT               NaT    red 39 days 14:54:43
5    111   xas              NaT  39 days 14:55:23   blue  0 days 00:05:22