Pandas:沿运行时定义的每一行列的映射函数(使用 *args)

use*_*067 6 python dataframe pandas

我想使用 *args 对 Pandas DataFrame 的行数据应用函数。可以这样完成(检索最大行的玩具示例):

df = pd.DataFrame(np.random.randint(0,100,size=(100, 4)), columns=list('ABCD'))
def f(*args):
   cols = [c for c in args]
   return max(cols)

m = list(map(f,df['A'],df['B'],df['C'],df['D']))
Run Code Online (Sandbox Code Playgroud)

有没有办法以这种方式做到这一点,而不必单独列出所有列?例如,当数据帧具有在运行时定义的任意列时。

找到最大值也可以用更简单的方法来完成,但是如何将任意函数应用于行(如果 *args 不可能)

jez*_*ael 12

看来您需要按行apply进行axis=1处理,并将每一行转换为Series

def f(x):
   print (x) 
   #sample function
   return x.max()

print (df.apply(f, axis=1))
Run Code Online (Sandbox Code Playgroud)

样本:

np.random.seed(45)
df = pd.DataFrame(np.random.randint(0,100,size=(3, 4)), columns=list('ABCD'))
print (df)
    A   B   C   D
0  75  30   3  32
1  95  61  85  35
2  68  15  65  14

def f(x):
   print (x) 
   #sample function
   return x.max()

A    75
B    30
C     3
D    32
Name: 0, dtype: int32
A    95
B    61
C    85
D    35
Name: 1, dtype: int32
A    68
B    15
C    65
D    14
Name: 2, dtype: int32
Run Code Online (Sandbox Code Playgroud)
print (df.apply(f, axis=1))
0    75
1    95
2    68
dtype: int64
Run Code Online (Sandbox Code Playgroud)

如果需要列表:

print (df.apply(f, axis=1).tolist())
[75, 95, 68]
Run Code Online (Sandbox Code Playgroud)