jeudi 29 juillet 2021

Python how to use if statement for dynamic column header

I have many csv files to be read by python and use pivot_table, but one of columns may not contain the same content for each csv file. After I use a fixed If Statement to execute a function, there will be an error.

For example, here's my code:

import pandas as pd
import numpy as np

dic = {
"Category": ['Math', 'Math', 'Math', 'Math', 'Math', 'Math', 'History', 'History','History','History','History','History','Physics','Physics','Physics','Physics','Physics','Physics'], 
"Name": ['John', 'Mary', 'Scott','Kevin','Judy','Lee','John', 'Mary', 'Scott','Kevin','Judy','Lee','John', 'Mary', 'Scott','Kevin','Judy','Lee'],
"Scores": [59,64,50,33,80,20,30,44,65,66,78,80,94,56,55,61,12,11]}

df = pd.DataFrame(dic)

df2=df.pivot_table(index= ['Name'], columns="Category", values=['Scores'])
 
df2.columns=df2.columns.droplevel(0)

if ((df2['History'] > 60) | (df2['Math'] > 70) | (df2['Physics'] > 50)).any():
     print (df2.loc[:, 'History'])

Above If Statement code works when the Category column in my csv file contains Math, History and Physics.

However, if the Category column in another csv file only have Math, History. The If Statement won't work. How can I solve the If statement to fit different scenario of dynamic column content?

For example below, this code won't work because there's no Physics in the column header.

import pandas as pd
import numpy as np

dic = {
"Category": ['Math', 'Math', 'Math', 'Math', 'Math', 'Math','Physics','Physics','Physics','Physics','Physics','Physics'], 
"Name": ['John', 'Mary', 'Scott','Kevin','Judy','Lee','John', 'Mary', 'Scott','Kevin','Judy','Lee','John', 'Mary', 'Scott','Kevin','Judy','Lee'],
"Scores": [59,64,50,33,80,20,30,44,65,66,78,80]}

df = pd.DataFrame(dic)

df2=df.pivot_table(index= ['Name'], columns="Category", values=['Scores'])
 
df2.columns=df2.columns.droplevel(0)

if ((df2['History'] > 60) | (df2['Math'] > 70) | (df2['Physics'] > 50)).any():
     print (df2.loc[:, 'History'])

Aucun commentaire:

Enregistrer un commentaire