亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

在 Python 中使用 .apply() 時如何獲取行的索引?

在 Python 中使用 .apply() 時如何獲取行的索引?

慕的地8271018 2023-01-04 16:21:38
我有一個包含列表行的數據框,如下所示:In [11]: import pandas as pdIn [12]: str1 = 'The weight of a apple'         str2 = 'Apple MacBook release date news and rumors'         list1 = ['DET', 'NOUN', 'ADP', 'DET', 'NOUN']         list2 = ['PROPN', 'NOUN', 'NOUN', 'NOUN', 'CCONJ', 'PROPN']         df = pd.DataFrame(             {                 'col1': [str1, str2],                 'col2': [list1, list2]                     }         )         dfOut[12]:                                          col1                                        col2  0                       The weight of a apple                 [DET, NOUN, ADP, DET, NOUN]1  Apple MacBook release date news and rumors     [PROPN, NOUN, NOUN, NOUN, CCONJ, PROPN]我正在使用用戶定義的函數來檢查col1中關鍵字“apple”的出現并通過使用 Pandas 中的 .apply() 獲取其位置值。然后我試圖從col2匹配位置值的列表中獲取項目。但是,當 .apply() 函數循環遍歷我的用戶定義函數時,我不知道如何獲取當前行的索引。這就是我想要做的。In [14]: # Find occurance of 'apple' keyword         def find_apple(text):           keyword = 'apple'           words = text.lower().split(' ')           if keyword in words:                 word_index = words.index(keyword)             value = df.col2[curr_row_index][word_index]             print(value)           else:             print('None')             # Function call using .apply()          df['col3'] = df['col1'].apply(find_apple)我想知道如何獲得curr_row_index的值,以便在數據幀的行上獲得可迭代的值。我試過使用 df.index 和 row.name 無濟于事。也許有人可以解釋我做錯了什么。PS 我是新來的,這是我第一次提出問題,因此對于任何遺漏的信息提前致歉。
查看完整描述

1 回答

?
慕蓋茨4494581

TA貢獻1850條經驗 獲得超11個贊

重構您的函數以對行進行操作,然后axis=1在調用應用程序時使用:


def f(row):

    #print(row.name,row.col1,row.col2)

    value = None

    if 'apple' in row.col1.lower():

        idx = row.col1.lower().split().index('apple')

#        print(row.col2[idx])

        value = row.col2[idx]

    return value


df['col3' ] = df.apply(f,axis=1)

使用您的示例 DataFrame:


In [34]: print(df.to_string())

                                         col1                                     col2   col3

0                       The weight of a apple              [DET, NOUN, ADP, DET, NOUN]   NOUN

1  Apple MacBook release date news and rumors  [PROPN, NOUN, NOUN, NOUN, CCONJ, PROPN]  PROPN


In [35]: 


查看完整回答
反對 回復 2023-01-04
  • 1 回答
  • 0 關注
  • 284 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號