【发布时间】:2019-02-15 05:20:08
【问题描述】:
我尝试使用函数计算系列中最频繁的元素循环 DataFrame 的行。当我手动向其中提供系列时,该功能可以完美运行:
# Create DataFrame
df = pd.DataFrame({'a' : [1, 2, 1, 2, 1, 2, 1, 1],
'b' : [1, 1, 2, 1, 1, 1, 2, 2],
'c' : [1, 2, 2, 1, 2, 2, 2, 1]})
# Create function calculating most frequent element
from collections import Counter
def freq_value(series):
return Counter(series).most_common()[0][0]
# Test function on one row
freq_value(df.iloc[1])
# Another test
freq_value((df.iloc[1, 0], df.iloc[1, 1], df.iloc[1, 2]))
通过这两个测试,我得到了想要的结果。但是,当我尝试在循环中通过 DataFrame 行应用此函数并将结果保存到新列中时,我收到错误 "'Series' object is not callable", 'occurred at index 0'。产生错误的行如下:
# Loop trough rows of a dataframe and write the result into new column
df['result'] = df.apply(lambda row: freq_value((row('a'), row('b'), row('c'))), axis = 1)
apply() 函数中的 row() 究竟是如何工作的?它不应该提供给我的freq_value() 'a'、'b'、'c' 列的函数值吗?
【问题讨论】:
-
在 apply 调用中尝试 row['a'] 而不是 row('a')。