【问题标题】:How to get the index of row when using .apply() in Python?在 Python 中使用 .apply() 时如何获取行的索引?
【发布时间】:2020-06-09 13:27:21
【问题描述】:

我有一个包含多行列表的数据框,如下所示:

In [11]: import pandas as pd

In [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]        
             }
         )

         df

Out[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]

我正在使用用户定义的函数来检查关键字“apple”在 col1 中的出现,并通过在 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 无济于事。也许有人可以解释我做错了什么。

附:我是新来的,这是我第一次提出问题,因此对于任何遗漏的信息提前道歉。

【问题讨论】:

  • 您希望 'col3' 使用您的示例 DataFrame 做什么?
  • 'col3 将拥有来自 'col2' 列表中的项目

标签: python pandas indexing apply


【解决方案1】:

重构您的函数以对行进行操作,然后在调用 apply 时使用 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-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-14
    • 1970-01-01
    • 1970-01-01
    • 2013-09-18
    相关资源
    最近更新 更多