I am relatively new to working with python and pandas and I'm trying to get the value of a cell in an excel sheet with python. To make matters worse, the excel sheet I'm working with doesn't have proper column names.
Here's what the dataframe looks like:
Sign Name 2020-09-05 2020-09-06 2020-09-07
JD John Doe A A B
MP Max Power B B A
What I want to do is to print the value of the "cell" where the column header is the current date and the sign is "MP".
What I've tried so far is this:
import pandas as pd
from datetime import datetime
time=datetime.now()
relevant_sheet = time.strftime("%B" " %y")
current_day = time.strftime("%Y-%m-%d")
excel_file = pd.ExcelFile('theexcelfile.xlsx')
df = pd.read_excel(excel_file, relevant_sheet, skiprows=[0,1,2,3]) # I don't need these
relevant_value = df.loc[df['Sign'] == "MP", df[current_day]]
This gives me a key error for current_day:
KeyError: '2020-09-07'
To fully disclose any possible issue with the real dataframe I'm working with: If I just print the dataframe, I get columns that look like this:
2020-09-01 00:00:00
Which is why I also tried:
current_day = time.strftime("%Y-%m-%d 00:00:00")
Of course I also "manually" tried all kinds of date formats, but to no avail. Am I going entirely wrong about this? Is this excel screwing with me?
To get the number of rows, and columns we can use len(df. axes[]) function in Python.
If in columns names are datetimes use Timestamp.floor
for remove times (set them to 00:00:00
):
current_day = pd.to_datetime('now').floor('d')
print (current_day)
2020-09-07 00:00:00
relevant_value = df.loc[df['Sign'] == "MP", current_day]
If in columns names are datetimes in strings format use:
relevant_value = df.loc[df['Sign'] == "MP", current_day]
If there are python dates:
current_day = pd.to_datetime('now').date()
print (current_day)
2020-09-07
relevant_value = df.loc[df['Sign'] == "MP", current_day]
You need to pass column name only instead of df[col_name].
Look .loc[] for detail.
df.loc[df['Sign'] == "MP", current_day]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With