gpt4 book ai didi

Python 3.5 - Pandas - 从另一个方法调用带有 for 循环的方法

转载 作者:太空宇宙 更新时间:2023-11-03 16:43:55 25 4
gpt4 key购买 nike

背景:

我正在将 Python 3.5 与 Pandas 和 Jupyter Notebook 结合使用。这是我第一次尝试类。使用 Jupyter Notebook 可以简单地运行一小部分一次对一个单元格进行编码。我想开始制作具有逻辑性且更易读的流程的脚本/程序。但是这里有我还不明白的基础知识。你知道我最近几天花了很多时间阅读并尝试一些方法来使其发挥作用。我很少问关于SO的问题因为我通常可以从以前的帖子中得到我需要的东西......就像大多数人一样我确定。

出于某种原因,我只是不知道如何做我确信很简单的事情。以下是我正在编写的一个大型程序的片段。此时有四种方法并且它们是重复的相同的代码。那就是循环通过 state_list 来过滤 Pandas 中我想要的状态我正在读入的数据帧。每个方法的目的是读入不同的文件(xlsx 和 csv)并提取日期和特定状态的数据。

我可以不用在每个方法中重复 for 循环吗使其成为一个方法,然后从其他方法中调用它?我尝试了几个事情,但它刚刚发生。

当前代码:

class GetData(object):

report_date = '3/1/2016'
state_list = ['AL', 'AZ', 'GA', 'IA', 'ID', 'IL', 'MN', 'MS',
'MT', 'NE', 'NM', 'NV', 'TN', 'UT', 'WI']


def data_getter(self):
"""Pulls in dataset and filters on specific date and states."""

data = pd.read_excel('C:\\datapath\\file.xlsx')
data = data[data['date'] == GetData.report_date]

states = []
for state in GetData.state_list:
df = data[data['state'] == state]
states.append(df)
concat_data = pd.concat(states, axis=0)
return concat_data

然后我像这样实例化它:

data = GetData()
dataset = data.data_getter()

目标 - 像这样的东西吗?

class GetData(object):

report_date = '3/1/2016'
state_list = ['AL', 'AZ', 'GA', 'IA', 'ID', 'IL', 'MN', 'MS',
'MT', 'NE', 'NM', 'NV', 'TN', 'UT', 'WI']


def data_getter(self):
"""Pulls in dataset and filters on specific date and states."""

data = pd.read_excel('C:\\datapath\\file.xlsx')
data = data[data['date'] == GetData.report_date]

# Call to state_filter here?

data = GetData()
data = data.state_filter

def state_filter(self):
states = []
for state in GetData.state_list:
df = data[data['state'] == state]
states.append(df)
concat_data = pd.concat(states, axis=0)
return concat_data

最佳答案

更新:

好吧,你总是可以编写自己的包装类,但我想说一定有一个很好的理由......

class GetData(object):

#report_date = '3/1/2016'
states = ['AL', 'AZ', 'GA', 'IA', 'ID', 'IL', 'MN', 'MS',
'MT', 'NE', 'NM', 'NV', 'TN', 'UT', 'WI']

def __init__(self, df_or_file=None, read_func=pd.read_excel, **kwargs):
if df_or_file is not None:
if isinstance(df_or_file, (pd.DataFrame, pd.Series, pd.Panel)):
self.data = df
elif(os.path.isfile(df_or_file)):
self.data = read_func(df_or_file, **kwargs)
else:
self.data = pd.DataFrame()

def save(self, filename, savefunc=pd.DataFrame.to_excel, **kwargs):
savefunc(df, filename, **kwargs)

现在您可以执行以下操作:

让我们生成一些随机 DF 并准备 CSV 和 Excel 文件:

In [53]: df = pd.DataFrame(np.random.randint(0, 10, size=(5, 3)), columns=list('abc'))

In [54]: df
Out[54]:
a b c
0 6 0 2
1 8 1 5
2 5 5 4
3 0 4 1
4 5 4 2

In [55]: df.to_csv('d:/temp/test.csv', index=False)

In [56]: (df+100).to_excel('d:/temp/test.xlsx', index=False)

现在我们可以创建我们的对象了:

In [57]: x = GetData(df)

In [58]: x.data
Out[58]:
a b c
0 6 0 2
1 8 1 5
2 5 5 4
3 0 4 1
4 5 4 2

或从 CSV 加载

In [61]: x = GetData('d:/temp/test.csv', read_func=pd.read_csv, sep=',')

In [62]: x.data
Out[62]:
a b c
0 6 0 2
1 8 1 5
2 5 5 4
3 0 4 1
4 5 4 2

In [63]: x.data[x.data.a == 5]
Out[63]:
a b c
2 5 5 4
4 5 4 2

或从 Excel 文件加载:

In [64]: x = GetData('d:/temp/test.xlsx')

In [65]: x.data
Out[65]:
a b c
0 106 100 102
1 108 101 105
2 105 105 104
3 100 104 101
4 105 104 102

并保存:

In [66]: x.data.c = 0

In [67]: x.data
Out[67]:
a b c
0 106 100 0
1 108 101 0
2 105 105 0
3 100 104 0
4 105 104 0

In [68]: x.save('d:/temp/new.xlsx', index=False)

In [69]: x.save('d:/temp/new.csv', savefunc=pd.DataFrame.to_csv, sep=';', index=False)

关于Python 3.5 - Pandas - 从另一个方法调用带有 for 循环的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36517507/

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