Dheeraj
Dheeraj

Reputation: 1202

Replace nan values with the unique date (date in numpy array.)

I have written a code in a for loop:

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

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

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

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

My approach:

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

there is an edit.

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)]

Expected Output:

   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?

Any help would be appreciated.

Upvotes: 1

Views: 5393

Answers (1)

Alexander
Alexander

Reputation: 109528

.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)]'

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'

Upvotes: 2

Related Questions