使用 lambda 的 pandas DataFrame.assign() 行为说明
Explanation of pandas DataFrame.assign() behaviour using lambda
import pandas as pd
import numpy as np
np.random.seed(99)
rows = 10
df = pd.DataFrame ({'A' : np.random.choice(range(0, 2), rows, replace = True),
'B' : np.random.choice(range(0, 2), rows, replace = True)})
def get_C1(row):
return row.A + row.B
def get_C2(row):
return 'X' if row.A + row.B == 0 else 'Y'
def get_C3(row):
is_zero = row.A + row.B
return "X" if is_zero else "Y"
df = df.assign(C = lambda row: get_C3(row))
为什么 get_C2 和 get_C3 函数 return 出错?
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
您认为 df.assign
在传递一个函数时表现得像 df.apply
和 axis=1
,它为每一行调用函数。
这是不正确的。
Where the value is a callable, evaluated on df
这意味着您传递给 assign
的函数是针对 整个数据帧 而不是 每一行 调用的。
所以,在你的函数get_C3
中,row
参数根本就不是一行。这是一个完整的数据框(应该重命名为 df
或其他名称),因此 row.A
和 row.B
是两个完整的列,而不是单个单元格值。
因此,is_zero
也是一整列,... if is_zero ...
将不起作用。
import pandas as pd
import numpy as np
np.random.seed(99)
rows = 10
df = pd.DataFrame ({'A' : np.random.choice(range(0, 2), rows, replace = True),
'B' : np.random.choice(range(0, 2), rows, replace = True)})
def get_C1(row):
return row.A + row.B
def get_C2(row):
return 'X' if row.A + row.B == 0 else 'Y'
def get_C3(row):
is_zero = row.A + row.B
return "X" if is_zero else "Y"
df = df.assign(C = lambda row: get_C3(row))
为什么 get_C2 和 get_C3 函数 return 出错?
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
您认为 df.assign
在传递一个函数时表现得像 df.apply
和 axis=1
,它为每一行调用函数。
这是不正确的。
Where the value is a callable, evaluated on df
这意味着您传递给 assign
的函数是针对 整个数据帧 而不是 每一行 调用的。
所以,在你的函数get_C3
中,row
参数根本就不是一行。这是一个完整的数据框(应该重命名为 df
或其他名称),因此 row.A
和 row.B
是两个完整的列,而不是单个单元格值。
因此,is_zero
也是一整列,... if is_zero ...
将不起作用。