python - 在一个类中设置一个函数,该函数将以一种可以在未来函数中引用的方式读取 csv 数据
问题描述
如果满足条件,我正在尝试确定在读取特定 .csv 文件的类中定义函数的最佳方法。然后,该函数返回文件中的数据。但我需要它以允许我在类中的未来函数中再次调用这些数据的方式返回数据。
一些背景知识:我正在读取的数据是带有时间戳的温度。每个 .csv 文件中的列是'day', 'hour', 'temp_1', 'temp_2', 'temp_3', 'temp_4'
然后,一年中的每个小时都有数字数据行,因此大约 9,000 行。
我需要定义一个从 csv 文件中读取数据的函数,然后允许我在未来的函数中调用临时数据以及相应的日期和时间。
### Here I define the class. I just included a shortened version of this.
### The class has more arguments than this. I just included the relevant parameter which is 'group'
class Individual():
def __init__(self,group):
self.group = group
### This is the function, or set of functions, that I'm trying to get running
def return_temp1(self, day, hour):
if self.group =='a':
micro_df = pd.read_csv('ex1.csv')
elif self.group =='b':
micro_df = pd.read_csv('ex2.csv')
return micro_df.temp1,day,hour
def return_temp2(self, day, hour):
if self.group =='a':
micro_df = pd.read_csv('ex1.csv')
elif self.group =='b':
micro_df = pd.read_csv('ex2.csv')
return micro_df.temp2,day,hour
def return_temp3(self, day, hour):
if self.group =='a':
micro_df = pd.read_csv('ex1.csv')
elif self.group =='b':
micro_df = pd.read_csv('ex2.csv')
return micro_df.temp3,day,hour
def return_temp4(self, day, hour):
if self.group =='a':
micro_df = pd.read_csv('ex1.csv')
elif self.group =='b':
micro_df = pd.read_csv('ex2.csv')
return micro_df.temp4,day,hour
### Then, later I need to define more functions where I'm able to call
# on the temperatures pulled from the csv files in the above functions.
# I've included one of those functions below as an example.
def calculate_longwave_radiation(self, temp1):
return 53.1*10**-14*(temp1 +273.15)**6.
我对 Python 很陌生,对使用类也很陌生。任何帮助或提示将不胜感激!我知道我设置return
线路的方式导致问题(或至少部分问题)......但我不知道如何解决它。谢谢你。
解决方案
我将在这里使用一种可能不是最好的 Python 语言的语言,但由于您是 Python 新手,它可能会在此过程中为您提供指导。
您在代码中使用的 pd 或 pandas 数据框就像 excel 工作表或表格。
因此,您可以做的是在您的类中创建一个名为 load_data() 的 def,然后分别在 df_ex1 和 df_ex2 中加载 ex1.csv 和 ex2.csv。如果它们具有相同的格式,您还可以将数据连接到单个 df 中。那些 dfs 应该是类的属性。喜欢:
class Individual():
def __init__(self,group):
self.group = group
df_ex1 = pd.DataFrame
完成上述操作后,您可以创建所需的所有定义并引用数据框以从中提取数据。喜欢
def return_temp1(self, day, hour):
if self.group =='a':
micro_df = df_ex1[['day', 'hour']].loc[df_ex1['day'] == day])
return micro_df
推荐阅读
- jquery - 如何将 JQUERY 数据表内容获取到 MVC 控制器
- java - Gson 不使用 Java 中的父类
- sql-server - SQL Server 存储过程的函数序列错误
- java - 在 Eclipse JDT Java 解析器中,是否可以在不使用访问者的情况下逐节点遍历 AST?
- c# - 正确调用另一个类的方法?
- node.js - node.js 语法错误:SyntaxError: Unexpected end of input
- regex - 正则表达式选择所有搜索字符串后,不包括搜索字符串
- javascript - 将对象引用传递给 jQuery 回调
- amazon-web-services - Docker 容器参数连接到 terraform 作业
- reactjs - 请求的项目在 Reactjs 中被隔离