我有一个包含列表行的数据框,如下所示:
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]
我正在使用用户定义的函数来检查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 我是新来的,这是我第一次提出问题,因此对于任何遗漏的信息提前致歉。
慕盖茨4494581
相关分类