我想两列转换为开始和结束的两列:
begin end
0 NaN 2019-10-21 07:48:28.272688
1 NaN 2019-10-21 07:48:28.449916
2 2019-10-21 07:48:26.740378 NaN
3 2019-10-21 07:48:26.923764 NaN
4 NaN 2019-10-21 07:48:41.689466
5 2019-10-21 07:48:37.306045 NaN
6 NaN 2019-10-21 07:58:00.774449
7 2019-10-21 07:57:59.223986 NaN
8 NaN 2019-10-21 08:32:37.004455
9 2019-10-21 08:32:35.755252 NaN
与另一列标志一起进入一个列时间戳:
Timestamp Flag
0 2019-10-21 07:48:28.272688 end
1 2019-10-21 07:48:28.449916 end
2 2019-10-21 07:48:26.740378 begin
3 2019-10-21 07:48:26.923764 begin
4 2019-10-21 07:48:41.689466 end
5 2019-10-21 07:48:37.306045 begin
6 2019-10-21 07:58:00.774449 end
7 2019-10-21 07:57:59.223986 begin
8 2019-10-21 08:32:37.004455 end
9 2019-10-21 08:32:35.755252 begin
但是目前我找不到将两列开始和结束合并为一个的解决方案。
谢谢您的时间!
答案 0 :(得分:2)
使用numpy.where()
:
df['Timestamp'] = np.where(df['begin'].isna(), df['end'], df['begin'])
df['flag'] = np.where(df['begin'].isna(), ['end'],['begin'])
如果您的空值NaN
是字符串,则将其用作条件。
答案 1 :(得分:2)
使用stack
和reset_index
:
(df.stack()
.rename_axis([None, 'Flag'])
.reset_index(level=1, name='Timestamp'))
[出]
Flag Timestamp
0 end 2019-10-21 07:48:28.272688
1 end 2019-10-21 07:48:28.449916
2 begin 2019-10-21 07:48:26.740378
3 begin 2019-10-21 07:48:26.923764
4 end 2019-10-21 07:48:41.689466
5 begin 2019-10-21 07:48:37.306045
6 end 2019-10-21 07:58:00.774449
7 begin 2019-10-21 07:57:59.223986
8 end 2019-10-21 08:32:37.004455
9 begin 2019-10-21 08:32:35.755252