时间增量到熊猫数据框中的字符串类型

Che*_* Su 8 python timedelta pandas

我有一个数据框df,它的第一列是timedelta64

df.info():

<class 'pandas.core.frame.DataFrame'>
RangeIndex: 686 entries, 0 to 685
Data columns (total 6 columns):
0    686 non-null timedelta64[ns]
1    686 non-null object
2    686 non-null object
3    686 non-null object
4    686 non-null object
5    686 non-null object
Run Code Online (Sandbox Code Playgroud)

print(df[0][2])例如,如果 I ,它会给我0 days 05:01:11。但是,我不想要0 days归档。我只想05:01:11被打印。有人可以教我如何做到这一点吗?非常感谢!

jez*_*ael 6

可以通过以下方式:

df['duration1'] = df['duration'].astype(str).str[-18:-10]
Run Code Online (Sandbox Code Playgroud)

但是解决方案不是通用的,如果输入也是3 days 05:01:11删除3 days

因此,解决方案仅适用于比一天少的 timedeltas。

更通用的解决方案是创建自定义格式

N = 10
np.random.seed(11230)
rng = pd.date_range('2017-04-03 15:30:00', periods=N, freq='13.5H')
df = pd.DataFrame({'duration': np.abs(np.random.choice(rng, size=N) - 
                                 np.random.choice(rng, size=N)) })  

df['duration1'] = df['duration'].astype(str).str[-18:-10]

def f(x):
    ts = x.total_seconds()
    hours, remainder = divmod(ts, 3600)
    minutes, seconds = divmod(remainder, 60)
    return ('{}:{:02d}:{:02d}').format(int(hours), int(minutes), int(seconds)) 

df['duration2'] = df['duration'].apply(f)
print (df)

         duration duration1  duration2
0 2 days 06:00:00  06:00:00   54:00:00
1 2 days 19:30:00  19:30:00   67:30:00
2 1 days 03:00:00  03:00:00   27:00:00
3 0 days 00:00:00  00:00:00    0:00:00
4 4 days 12:00:00  12:00:00  108:00:00
5 1 days 03:00:00  03:00:00   27:00:00
6 0 days 13:30:00  13:30:00   13:30:00
7 1 days 16:30:00  16:30:00   40:30:00
8 0 days 00:00:00  00:00:00    0:00:00
9 1 days 16:30:00  16:30:00   40:30:00
Run Code Online (Sandbox Code Playgroud)


Sim*_* G. 6

这是一个简短而强大的版本,使用apply()

df['timediff_string'] = df['timediff'].apply(
    lambda x: f'{x.components.hours:02d}:{x.components.minutes:02d}:{x.components.seconds:02d}'
              if not pd.isnull(x) else ''
)
Run Code Online (Sandbox Code Playgroud)

这利用了Pandas Timedelta 对象的components属性并处理空值 (NaT)。

如果timediff列不包含 Pandas Timedelta 对象,则可以对其进行转换:

df['timediff'] = pd.to_timedelta(df['timediff'])
Run Code Online (Sandbox Code Playgroud)