【发布时间】: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