用多个参数应用函数来创build一个新的pandas列
我想通过将一个函数应用于两个现有的列,在pandas数据框架中创build一个新的列。 在回答这个问题之后,我只需要一列就可以创build一个新的列: 
 import pandas as pd df = pd.DataFrame({"A": [10,20,30], "B": [20, 30, 10]}) def fx(x): return x * x print(df) df['newcolumn'] = df.A.apply(fx) print(df) 
不过,当函数需要多个参数时,我无法弄清楚如何做同样的事情。 例如,如何通过将列A和列B传递给下面的函数来创build新列?
 def fxy(x, y): return x * y 
	
或者,您可以使用numpy底层函数:
 >>> import numpy as np >>> df = pd.DataFrame({"A": [10,20,30], "B": [20, 30, 10]}) >>> df['new_column'] = np.multiply(df['A'], df['B']) >>> df AB new_column 0 10 20 200 1 20 30 600 2 30 10 300 
或在一般情况下vector化任意函数:
 >>> def fx(x, y): ... return x*y ... >>> df['new_column'] = np.vectorize(fx)(df['A'], df['B']) >>> df AB new_column 0 10 20 200 1 20 30 600 2 30 10 300 
如果可以重写你的函数,你可以使用@greenAfrican的例子。 但是如果你不想重写你的函数,你可以把它封装到匿名函数中,如下所示:
 >>> def fxy(x, y): ... return x * y >>> df['newcolumn'] = df.apply(lambda x: fxy(x['A'], x['B']), axis=1) >>> df AB newcolumn 0 10 20 200 1 20 30 600 2 30 10 300 
这解决了这个问题:
 df['newcolumn'] = df.A * df.B 
你也可以这样做:
 def fab(row): return row['A'] * row['B'] df['newcolumn'] = df.apply(fab, axis=1) 
多一个字典样式干净的语法:
 df["new_column"] = df.apply(lambda x: x["A"] * x["B"], axis = 1) 
要么,
 df["new_column"] = df["A"] * df["B"] 
如果您需要一次创build多个列 :
- 
创build数据框: import pandas as pd df = pd.DataFrame({"A": [10,20,30], "B": [20, 30, 10]})
- 
创buildfunction: def fab(row): return row['A'] * row['B'], row['A'] + row['B']
- 
分配新列: df['newcolumn'], df['newcolumn2'] = zip(*df.apply(fab, axis=1))