我有一個包含在線和離線資料的類,我想使用一個可以根據現有列過濾資料的函式。以下代碼有效:
class Exp:
def __init__(self):
d = {'col1': [1, 2], 'col2': [3, 4], 'col3' : [5,6]}
d2 = {'col1': [7, 8], 'col2': [9, 10], 'col3' : [11,12]}
self.online = pd.DataFrame(d)
self.offline = pd.DataFrame(d2)
def filter_cols(self, typ, cols):
if typ == "on":
self.online = self.online.filter(items= cols)
if typ == "off":
self.offline = self.offline.filter(items = cols)
print("before")
a = Exp()
print(a.online)
a.filter_cols("on", cols = ['col1', 'col2'])
print("after")
print(a.online)
結果:
before
col1 col2 col3
0 1 3 5
1 2 4 6
after
col1 col2
0 1 3
1 2 4
但我想讓我的函式更通用,這樣我就不必在函式中指定 if 和 else 陳述句。所以基本上我想要像下面這樣的東西
class Exp:
.
.
.
def filter_cols(self, data, cols):
data.filter(items= cols)
print("before")
a = Exp()
print(a.online)
a.filter_cols(a.online, cols = ['col1', 'col2'])
print("after")
print(a.online)
但結果還是一樣:
before
col1 col2 col3
0 1 3 5
1 2 4 6
after
col1 col2 col3
0 1 3 5
1 2 4 6
uj5u.com熱心網友回復:
使用setattr并getattr像這樣:
def filter_cols(self, typ, cols):
setattr(self, typ 'line', getattr(self, typ 'line').filter(items= cols))
完整代碼:
class Exp:
def __init__(self):
d = {'col1': [1, 2], 'col2': [3, 4], 'col3' : [5,6]}
d2 = {'col1': [7, 8], 'col2': [9, 10], 'col3' : [11,12]}
self.online = pd.DataFrame(d)
self.offline = pd.DataFrame(d2)
def filter_cols(self, typ, cols):
setattr(self, typ 'line', getattr(self, typ 'line').filter(items= cols))
print("before")
a = Exp()
print(a.online)
a.filter_cols("on", cols = ['col1', 'col2'])
print("after")
輸出:
before
col1 col2 col3
0 1 3 5
1 2 4 6
after
col1 col2
0 1 3
1 2 4
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/327271.html
