用唯一的日期(numpy数组中的日期)替换nan值. [英] Replace nan values with the unique date (date in numpy array.)

查看:64
本文介绍了用唯一的日期(numpy数组中的日期)替换nan值.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在for循环中编写了代码:

I have written a code in a for loop:

date = dit[x]["Time"].dt.date.unique()

output:
[datetime.date(2017, 6, 5)]

我得到了一个numpy数组.

I am getting a numpy array.

我有一个像这样的数据框:

I have a dataframe like this:

   Position  Values  Date
0       1.0  826.18   NaN
1      22.0  828.11   NaN
2      33.0  826.18   NaN
3      56.0  826.09   NaN

我想用上面代码中得到的唯一日期替换Nan值.

I want to replace Nan values with the unique date i am getting from the above code.

我的方法:

peaks_df["Date"] = peaks_df["Date"].replace(np.nan, str(date))

有一个编辑.

output:

   Position  Values                          Date
0       1.0  826.18  [datetime.date(2017, 6, 5)]
1      22.0  828.11  [datetime.date(2017, 6, 5)]
2      33.0  826.18  [datetime.date(2017, 6, 5)]
3      56.0  826.09  [datetime.date(2017, 6, 5)]

预期输出:

   Position  Values    Date
0       1.0  826.18  6/5/2017
1      22.0  828.11  6/5/2017
2      33.0  826.18  6/5/2017
3      56.0  826.09  6/5/2017

有人可以建议我正确的方法吗?

Can anybody suggest me the correct way to do it?

任何帮助将不胜感激.

推荐答案

.unique()返回所选内容中所有唯一元素的列表(可能不止一个).如果确定给定数据个日期,只需访问列表的第一个(也是唯一一个)元素即可.如果列表为空,则使用三元数,在这种情况下,它将返回一个空白字符串.

.unique() returns a list of all unique elements in the selection (there could be more than one). If you are sure that there will only be one date given your data, just access the first (and only) element of the list. I used a ternary in case the list is empty, in which case it returns a blank string.

.replace(np.nan, str(date[0]) if date else "")

您可能会通过以下方式注意到问题的根源:

You can probably notice the source of your problem via this:

>>> str([dt.date.today()])
'[datetime.date(2018, 1, 5)]'

您的date变量是一个包含单个日期的列表.将其转换为字符串会得到上面的输出.

Your date variable is a list containing a single date. Converting it to a string results in the output above.

但是,采用此列表的第一个元素会导致您期望的结果:

Taking the first element of this list, however, would result in your desired outcome:

>>> str([dt.date.today()][0])
'2018-01-05'

这篇关于用唯一的日期(numpy数组中的日期)替换nan值.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆