gpt4 book ai didi

python - 将数据帧作为类方法返回

转载 作者:行者123 更新时间:2023-12-01 08:08:07 25 4
gpt4 key购买 nike

我想在创建对象时创建作为数据框的报表对象。该代码旨在读取文件并作为实例化和调用加载方法的一部分进行一些过滤

class Report:
def __init__(self,c = ['red','green','blue'],y = [2015,2016,2017,2018,2019]):
self.color = c
self.years = y

def load(self):
df = pd.read_excel(r"C:\Users\ger\Desktop\sample.xlsx",sheet_name='sht1')
df = df.loc[(df['color'].isin(self.color) &
df['year'].isin(self.years)),:]
return df

# none of these below seems to work though
r1 = Report().load()

# or
r1 = Report()
r1 = r1.load()

预期结果将是具有颜色和年份字段的数据帧,如 init 中提到的或 Report() 调用中定义的。任何想法都非常感激

最佳答案

如果您的目标是将 load 作为实际的类方法,那么以下是适合您的情况的示例:

import pandas as pd

class Report:
def __init__(self, c=['red', 'green', 'blue'], y=[2017, 2018, 2019]):
self.color = c
self.years = y

@classmethod
def load(cls, self):
df = pd.DataFrame(
{'color': ['red', 'blue', 'green', 'yellow', 'purple'],
'year': [2015, 2016, 2017, 2018, 2019]}
)
df = df.loc[df['color'].isin(self.color) & df['year'].isin(self.years)]
self.df = df

实际操作:

>>> report = Report()
>>> Report.load(report)
>>> print(report.df)
color year
2 green 2017

关于python - 将数据帧作为类方法返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55432644/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com