【问题标题】:Class attributes to pandas dataframe熊猫数据框的类属性
【发布时间】:2022-12-10 02:01:30
【问题描述】:

我想知道如何让我的熊猫数据框从给定的类属性中获取数据。我的代码如下所示:

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'

我希望我的数据框最终看起来像这样:

Name            Round      Score

Kelly Slater    2          15.75

我想知道如何使用 pandas 获取 name_fullcontest_roundscore 属性来获取此数据框。

【问题讨论】:

    标签: python pandas


    【解决方案1】:
    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)
    

    【讨论】:

    • 如果你想改变什么。添加评论
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-09-30
    • 2020-08-08
    • 1970-01-01
    • 2021-11-09
    相关资源
    最近更新 更多