M_I*_*845 4 python apply dataframe python-3.x pandas
我正在尝试将具有多个参数的函数应用于数据框,其中两个参数需要分配给数据框的行,而一个是变量(简单数字)。
对于行,类似线程的变体适用:(与我的原始函数相比,所有函数都被简化了)
import pandas as pd
dict={'a':[-2,5,4,-6], 'b':[4,4,5,-8]}
df=pd.DataFrame (dict)
print(df)
def DummyFunction (row):
return row['a']*row['b']
#this works:
df['Dummy1']=df.apply(DummyFunction, axis=1)
Run Code Online (Sandbox Code Playgroud)
但是,如何在函数接受附加参数(固定变量)的情况下应用以下变体?我似乎找不到办法将它传递给apply方法:
def DummyFunction2(row, threshold):
return row['a']*row['b']*threshold
# where threshold will be assigned to a number?
# I don't seem to find a viable option to fill the row argument below:
# df['Dummy2']=df.apply(DummyFunction2(row,1000), axis=1)
Run Code Online (Sandbox Code Playgroud)
谢谢你的帮助!
您可以将其他变量直接作为命名参数传递给pd.DataFrame.apply:
def DummyFunction2(row, threshold):
return row['a']*row['b']*threshold
df['Dummy2'] = df.apply(DummyFunction2, threshold=2, axis=1)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1995 次 |
| 最近记录: |