1

Newbie at dealing with classes.

I have some dataframe objects I want to transform, but I'm having trouble manipulating them with classes. Below is an example. The goal is to transpose a dataframe and reassign it to its original variable name. In this case, the dataframe is assets.

import pandas as pd
from requests import get
import numpy as np

html = get("https://www.cbn.gov.ng/rates/Assets.asp").text

table = pd.read_html(html,skiprows=[0,1])[2]
assets = table[1:13]

class Array_Df_Retitle:
    def __init__(self,df):
        self.df = df
        
    def change(self):
        self.df = self.df.transpose()
        self.df.columns = self.df[0]
        return self.df

However, calling assets = Array_Df_Retitle(assets).change() simply yields an error:

KeyError: 0

I'd like to know where I'm getting things wrong.

1 Answer 1

2

I made a few changes to your code. The problem is coming from self.df[0]. This means you are selecting the column named 0. However, after transposing, you will not have any column named 0. You will have a row instead.

import pandas as pd
from requests import get
import numpy as np

html = get("https://www.cbn.gov.ng/rates/Assets.asp").text

table = pd.read_html(html,skiprows=[0,1])[2]
assets = table[1:13]

class Array_Df_Retitle:
    def __init__(self,df):
        self.df = df
        
    def change(self):
        self.df = self.df.dropna(how='all').transpose()
        self.df.columns = self.df.loc[0,:]
        return self.df.drop(0).reset_index(drop=True)


Array_Df_Retitle(assets).change()

enter image description here

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.