[英]Python call function within class using lambda expression
I have a class inside a .py file that contains two functions. 我在.py文件中有一个包含两个函数的类。
new_column
generates a new column based on values of existing columns (Col1 and Col2). new_column
根据现有列(Col1和Col2)的值生成新列。
transform_df
applies the previous function to a dataframe, via a lambda expression. transform_df
通过lambda表达式将前一个函数应用于数据帧。
The end result looks like this: 最终结果如下:
Col1 Col2 col3
0 a b ab
1 a b ab
2 a c None
3 a b ab
How do I use these functions in a new file/notebook? 如何在新文件/笔记本中使用这些功能?
# kept within file df_functions.py
class Functions():
def __init__(self, path):
self.path = path # path to .csv
# function to create new column, based on Col1 and Col2 values
def new_column(self, row):
if (row['Col1'] == 'a') & (row['Col2'] == 'b'):
return 'ab'
# apply previously defined function via lambda expression
def transform_df(self, path):
df = pd.read_csv(self.path)
# apply function 'new_column' to df
df['col3'] = df.apply(lambda row: self.new_column(row), axis=1)
# other potential functions applications here
return df
I have tried the following: 我尝试过以下方法:
from df_functions import Functions
df_path = '../datafile.csv'
FunctionsObject = Functions(path=df_path)
new_df = FunctionsObject.transform_df(path=df_path)
However this returns 然而这又回来了
NameError: ("name 'new_column' is not defined", 'occurred at index 0')
Appears to be a problem related to making edits to the .py file containing the class. 似乎是对包含该类的.py文件进行编辑的问题。 After making changes, I restarted the kernel and the imported functions work as expected. 进行更改后,我重新启动内核,导入的函数按预期工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.