我尝试使用函数计算系列中最频繁的元素来循环 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)
row()在apply()函数中究竟是如何工作的?它不应该freq_value()从“a”、“b”、“c”列提供给我的函数值吗?
呼唤远方
一只名叫tom的猫
眼眸繁星
繁花如伊
随时随地看视频慕课网APP
相关分类