給定數(shù)據(jù)框df = pd.DataFrame({'word1': ['elvis', 'lease', 'admirer'], 'word2': ['lives', 'sale', 'married']})如何添加第三列,根據(jù)同一行中的兩個單詞是否是字謎詞返回 True 或 False?我已經(jīng)編寫了這個函數(shù),當我將它應(yīng)用于 df.def anagram(word1, word2): word1_lst = [l for l in word1] word2_lst = [i for i in word2] return sorted(word1_lst) == sorted(word2_lst)df['Anagram'] = df.apply(anagram(df['word1'], df['word2']), axis = 1)類型錯誤:“bool”對象不可調(diào)用
2 回答

汪汪一只貓
TA貢獻1898條經(jīng)驗 獲得超8個贊
df = pd.DataFrame({'word1': ['elvis', 'lease', 'admirer'], 'word2': ['lives', 'sale', 'married']}) df['Anagram'] = df.word1.apply(sorted) == df.word2.apply(sorted)

繁星淼淼
TA貢獻1775條經(jīng)驗 獲得超11個贊
這里的問題是您正在df.apply()
使用參數(shù)進行調(diào)用
anagram(df['word1'], df['word2')
這是一個布爾值,而不是一個函數(shù)
和
axis = 1
要修復(fù)此問題,請像這樣更改您的函數(shù):
def anagram(row): word1_lst = [l for l in row['word1']] word2_lst = [i for i in row['word2']] return sorted(word1_lst) == sorted(word2_lst)
然后用函數(shù)名調(diào)用方法,而不是結(jié)果
df['Anagram'] = df.apply(anagram, axis=1)
添加回答
舉報
0/150
提交
取消