Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python pandas print value where column = X and row = Y

Tags:

python

pandas

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?

like image 233
zebraartefakt Avatar asked Sep 07 '20 09:09

zebraartefakt


People also ask

How do I print the number of rows and columns in a DataFrame in python?

To get the number of rows, and columns we can use len(df. axes[]) function in Python.


2 Answers

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]
like image 84
jezrael Avatar answered Oct 28 '22 07:10

jezrael


You need to pass column name only instead of df[col_name].

Look .loc[] for detail.

df.loc[df['Sign'] == "MP", current_day]
like image 43
Sadiq Raza Avatar answered Oct 28 '22 06:10

Sadiq Raza