關於pandas之apply的使用錯誤情況,如‘str’ object is not callable和unhashable type

“原 DataFrame” 與 “使用了 groupby 之後的分組 DataFrame",在調用 apply 方法時,有些許差異

df = pd.DataFrame([[j for j in range(1, 5)] for i in range(5)], index=list("ABBDA"))
df
# Out[227]: 
#    0  1  2  3
# A  1  2  3  4
# B  1  2  3  4
# B  1  2  3  4
# D  1  2  3  4
# A  1  2  3  4

""" 1、直接使用函數名時,都能正常運行 """
df.apply(min, axis=1)
# Out[265]: 
# A    1
# B    1
# B    1
# D    1
# A    1
# dtype: int64

df.groupby(df.index).apply(min, axis=1)
# Out[276]: 
# A  A    1
#    A    1
# B  B    1
#    B    1
# D  D    1
# dtype: int64


""" 2、使用函數名的字符串形式時,進行了分組操作的 DataFrame 就會報錯 """
df.apply('min', axis=1)
# Out[288]: 
# A    1
# B    1
# B    1
# D    1
# A    1
# dtype: int64

# 報錯:AttributeError: 'DataFrame' object has no attribute 'dtype'
# df.groupby(df.index).apply('min', axis=1)

# 報錯:TypeError: 'str' object is not callable
# df.groupby(df.index).apply('min')



""" 3、傳入函數名列表的時候,進行了分組操作的 DataFrame 也會報錯 """
df.apply(['min', max], axis=1)
# Out[289]: 
#    min  max
# A    1    4
# B    1    4
# B    1    4
# D    1    4
# A    1    4

# 報錯:TypeError: unhashable type: 'list'
# df.groupby(df.index).apply([min, 'max'])
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章