为了账号安全,请及时绑定邮箱和手机立即绑定

在 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 关注
  • 182 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信