3 回答

TA贡献1906条经验 获得超3个赞
row不是您的 函数lambda,因此括号不合适,相反,您应该使用__getitem__方法或loc访问器来访问值。前者的语法糖是[]:
df['result'] = df.apply(lambda row: freq_value((row['a'], row['b'], row['c'])), axis=1)
使用loc替代方案:
def freq_value_calc(row):
return freq_value((row.loc['a'], row.loc['b'], row.loc['c']))
要准确理解为什么会出现这种情况,将您lambda的函数重写为命名函数会有所帮助:
def freq_value_calc(row):
print(type(row)) # useful for debugging
return freq_value((row['a'], row['b'], row['c']))
df['result'] = df.apply(freq_value_calc, axis=1)
运行这个,你会发现它row的类型是<class 'pandas.core.series.Series'>,即如果你使用axis=1. 要访问给定标签的系列中的值,您可以使用__getitem__/[]语法或loc.

TA贡献1873条经验 获得超9个赞
您也可以使用df.mode, 和来获得所需的结果axis=1。这将避免使用apply, 并且仍然会为您提供每行最常见值的列。
df['result'] = df.mode(1)
>>> df
a b c result
0 1 1 1 1
1 2 1 2 2
2 1 2 2 2
3 2 1 1 1
4 1 1 2 1
5 2 1 2 2
6 1 2 2 2
7 1 2 1 1
添加回答
举报