在同一Python类中使用其他类方法对类方法进行初始化
有人能凭直觉给我解释一下,为什么我可以根据下面的例子,使用我的另一个类方法循环这个类方法?我有另一个代码以同样的方式构建,用于更大的任务,完全遵循这个逻辑在同一Python类中使用其他类方法对类方法进行初始化,python,pandas,Python,Pandas,有人能凭直觉给我解释一下,为什么我可以根据下面的例子,使用我的另一个类方法循环这个类方法?我有另一个代码以同样的方式构建,用于更大的任务,完全遵循这个逻辑 import pandas as pd import numpy as np df = pd.DataFrame({'col1' : ['a', 'a', 'b','b','b','c','c'] ,'col2' : [1, np.nan, 2,2,np.nan,2,2]
import pandas as pd
import numpy as np
df = pd.DataFrame({'col1' : ['a', 'a', 'b','b','b','c','c']
,'col2' : [1, np.nan, 2,2,np.nan,2,2]
,'col3' : [1,2,3,4,5,6,7]
})
class test(object):
def __init__(self):
print ("Started an instance of a class")
def add(self, df):
self.df = df
self.df['col4'] = self.df['col2'] + self.df['col3']
return self.df['col4']
def subset(self, df, str_disc_grp):
self.df = df
self.str_disc_grp = str_disc_grp
list_disc_grp = self.df[self.str_disc_grp].drop_duplicates()
for disc_lvl in list_disc_grp:
print ("Itteration is for level: {}".format(disc_lvl))
df_sub = self.df[self.df[self.str_disc_grp] == disc_lvl]
df_temp = self.add(df_sub)
display(df_temp)
# do other stuff....
class_test = test()
# Dosent work
class_test.subset(df, str_disc_grp='col1')
下面是使用for循环的CLING类方法的结果,它似乎捕获了“col1”的其他级别:
Itteration is for level: a
0 2.0
1 NaN
Name: col4, dtype: float64
Itteration is for level: b
Series([], Name: col4, dtype: float64)
Itteration is for level: c
Series([], Name: col4, dtype: float64)
当然,按照下面的思路做一些事情是没有问题的:
# Does work
list_disc_lvl = df['col1'].drop_duplicates().tolist()
for subset_lvl in list_disc_lvl:
bool_temp = (df['col1'] == subset_lvl)
df_sub = df[bool_temp]
display(df_sub)
# do other stuff
以下循环的子选择汇总结果为正常值:
0 2.0
1 NaN
Name: col4, dtype: float64
2 5.0
3 6.0
4 NaN
Name: col4, dtype: float64
5 8.0
6 9.0
Name: col4, dtype: float64
提前谢谢!
/瑞典人