Home > Enterprise >  Class attributes to pandas dataframe
Class attributes to pandas dataframe

Time:12-10

I am wondering how I can go about getting my pandas dataframe to take data from given class attributes. My code looks like this:

import pandas as pd


class Surfers:
    def __init__(self):
        self.name_full: str = None
        self.contest_round: str = None
        self.score: str = None

    def __repr__(self):
        name_to_show: str = ''
        if self.name_full is not None:
            name_to_show = self.name_full
        round_to_show: str = ''
        if self.contest_round is not None:
            round_to_show = self.contest_round
        score_to_show: str = ''
        if self.score is not None:
            score_to_show = self.score
        return f"{name_to_show}, {round_to_show}, {score_to_show}"

#This is just an example, I am actually scraping to get these values
surfer1 = Surfers()
surfer1.contest_round = '2'
surfer1.name_full = "Kelly Slater"
surfer1.score = '15.75'

I want my dataframe to end up looking like this:

Name            Round      Score

Kelly Slater    2          15.75

I'm wondering how I can use pandas to take the name_full, contest_round, and score attributes to get this dataframe.

CodePudding user response:

import pandas as pd
# 

class Surfers:
    def __init__(self):
        self.name_full: str = None
        self.contest_round: str = None
        self.score: str = None

    def __repr__(self):
        name_to_show: str = ''
        if self.name_full is not None:
            name_to_show = self.name_full
        round_to_show: str = ''
        if self.contest_round is not None:
            round_to_show = self.contest_round
        score_to_show: str = ''
        if self.score is not None:
            score_to_show = self.score
        return f"{name_to_show}, {round_to_show}, {score_to_show}"

#This is just an example, I am actually scraping to get these values
surfer1 = Surfers()
surfer1.contest_round = '2'
surfer1.name_full = "Kelly Slater"
surfer1.score = '15.75'
str1 = str(surfer1)
data_list = str1.split(", ")
data = [data_list]
  
# Create the pandas DataFrame
df = pd.DataFrame(data, columns=['Name', 'Round', 'Score'])

print(df)
  • Related