繁体   English   中英

如何计算平均时间并在 python 的另一列中填写 nan?

[英]How to calculate the average time and fill the nan in another column in python?

输入数据:

from scene time      departure time           time
12/12/2017 20:01    12/12/2017 20:20           Nan
12/12/2017 22:09    12/12/2017 22:09           Nan
12/12/2017 23:00    12/12/2017 23:30           Nan
12/12/2017 22:37    12/12/2017 22:37           Nan
12/13/17 18:25      12/13/17   20:20        12/13/17 20:20
  • 在这里,需要使用前两列的平均值填充时间列的 nan 值,即从场景时间出发时间

  • 下面提到了预期的 output,我通常输入了值来代替 nan(例如)。

预期 output:

from scene time         departure time        handover time
    12/12/2017 20:01    12/12/2017 20:20     12/12/2017 20:19
    12/12/2017 22:09    12/12/2017 22:30     12/12/2017 22:16
    12/12/2017 23:00    12/12/2017 23:30     12/12/2017 23:22
    12/12/2017 22:37    12/12/2017 22:37           Nan
    12/13/17 18:25      12/13/17 20:20      12/13/17 20:20

利用:

#first convert columns to datetimes
cols = ['from scene time','departure time', 'time']
df[cols] = df[cols].apply(pd.to_datetime)

#create means by convert to numpy array
a = df[['from scene time','departure time']].to_numpy().astype(np.int64).mean(axis=1)
avg = pd.Series(pd.to_datetime(a), index=df.index)

#replace only missing values
df['time'] = df['time'].fillna(avg)
print (df)
      from scene time      departure time                time
0 2017-12-12 20:01:00 2017-12-12 20:20:00 2017-12-12 20:10:30
1 2017-12-12 22:09:00 2017-12-12 22:09:00 2017-12-12 22:09:00
2 2017-12-12 23:00:00 2017-12-12 23:30:00 2017-12-12 23:15:00
3 2017-12-12 22:37:00 2017-12-12 22:37:00 2017-12-12 22:37:00
4 2017-12-13 18:25:00 2017-12-13 20:20:00 2017-12-13 20:20:00

如果只有几行缺少值以提高性能,则仅对time列中缺少值的行应用解决方案:

cols = ['from scene time','departure time', 'time']
df[cols] = df[cols].apply(pd.to_datetime)

mask = df['time'].isna()

a=df.loc[mask,['from scene time','departure time']].to_numpy().astype(np.int64).mean(axis=1)

df.loc[mask, 'time'] = pd.to_datetime(a)
print (df)
      from scene time      departure time                time
0 2017-12-12 20:01:00 2017-12-12 20:20:00 2017-12-12 20:10:30
1 2017-12-12 22:09:00 2017-12-12 22:09:00 2017-12-12 22:09:00
2 2017-12-12 23:00:00 2017-12-12 23:30:00 2017-12-12 23:15:00
3 2017-12-12 22:37:00 2017-12-12 22:37:00 2017-12-12 22:37:00
4 2017-12-13 18:25:00 2017-12-13 20:20:00 2017-12-13 20:20:00

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM