anon1234345
anon1234345

Reputation: 25

How do I check my dates with this if statement?

I have some missing dates in a dataframe that I'm trying to fill in with the previous date. So I imagine the first part would be to check if holdings_df['date'] is in d. Hope you can help as I'm stuck.

Here's my function

In:

def get_holdings_df_date(d):
    if (d in holdings_df['Date'].values):
        # return holdings_df.loc[holdings_df['Date'] == d]
        print('true')

print(get_holdings_df_date('2020-01-02'))

Out:

FutureWarning: elementwise comparison failed; returning scalar instead, but in the future will perform elementwise comparison
  if (d in holdings_df['Date'].values):
None
Traceback (most recent call last):
  File "calculatingnav.py", line 130, in <module>
    system.exit()

Upvotes: 1

Views: 82

Answers (1)

Diogo Silva
Diogo Silva

Reputation: 330

This seems straightforward. Your function could look like this:

def get_holdings_df_date(d):
    return True if str(d) in holdings_df["Date"].values else False

Entire code sample:

import pandas as pd

test = [
    ("2020-01-02", 34, "Sydney", 155),
    ("2020-01-03", 31, "Delhi", 177),
    ("2020-01-04", 16, "Mumbai", 81),
    ("2020-01-05", 31, "Delhi", 167),
    ("2020-01-06", 81, "Delhi", 144),
    ("2020-01-07", 35, "Mumbai", 135),
    ("2020-01-08", 35, "Colombo", 111),
    ("2020-01-09", 32, "Colombo", 111),
]

holdings_df = pd.DataFrame(test, columns=["Date", "x", "y", "z"])


def get_holdings_df_date(d):
    return True if str(d) in holdings_df["Date"].values else False


print(get_holdings_df_date("2020-01-02"))

Outputs:

True

Upvotes: 1

Related Questions