Compare user input date to pandas df date

Question:

I’m trying to compare user input date (month and year format) to pandas df date column and pick the corresponding value on the df.

here is an example:

  birthDate = input("birth year-month?")
  deathDate = input("death year-month?")

  // assume that user inputs: 2-2022 and 3-2022

  df = pd.DataFrame({'date': ['1-2022', '2-2022', '3-2022'],
                   'value': [1.4, 1223.22, 2323.23]})

   output:
   "birth day value is 1223.22"
   "death day value is 2323.23"


Asked By: Xenophia

||

Answers:

try this one –

print("birth day value is", float(df[df["date"]==birthDate]["value"]))
print("death day value is", float(df[df["date"]==deathDate]["value"]))
Answered By: Rajkumar Hajgude
birthDate = input("birth month-year?")
deathDate = input("death month-year?")

birthday_value = df.loc[df["date"] == birthDate, "value"].values[0]
deathday_value = df.loc[df["date"] == deathDate, "value"].values[0]

print(f"birth day value is {birthday_value}") 
print(f"death day value is {deathday_value}") 

Output:

birth day value is 1223.22
death day value is 2323.23
Answered By: Jamiu Shaibu
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.