【发布时间】:2018-07-08 11:35:23
【问题描述】:
我正在尝试过滤(并因此更改)pandas 中依赖于其他列中的值的某些行。假设我的 dataFrame 如下所示:
SENT ID WORD POS HEAD
1 1 I PRON 2
1 2 like VERB 0
1 3 incredibly ADV 4
1 4 brown ADJ 5
1 5 sugar NOUN 2
2 1 Here ADV 2
2 2 appears VERB 0
2 3 my PRON 5
2 4 next ADJ 5
2 5 sentence NOUN 0
结构是这样的,“HEAD”列指向该行所依赖的单词的索引。例如,如果 'brown' 依赖于 'sugar' 那么 'brown' 的头部是 4,因为 'sugar' 的索引是 4。
我需要提取所有行的 df,其中 POS 是 ADV,其头部的 POS VERB,所以“这里”将在新的 df 中,但不是“难以置信”,(并可能对其 WORD 条目进行更改) . 目前我正在使用循环进行操作,但我认为这不是熊猫的方式,而且它还会在未来产生问题。这是我当前的代码(split("-") 来自另一个故事 - 忽略它):
def get_head(df, dependent):
head = dependent
target_index = int(dependent['HEAD'])
if target_index == 0:
return dependent
else:
if target_index < int(dependent['INDEX']):
# 1st int in cell
while (int(head['INDEX'].split("-")[0]) > target_index):
head = data.iloc[int(head.name) - 1]
elif target_index > int(dependent['INDEX']):
while int(head['INDEX'].split("-")[0]) < target_index:
head = data.iloc[int(head.name) + 1]
return head
我在编写这个函数时遇到的一个困难是我(当时)没有“句子”列,所以我不得不手动找到最近的头部。我希望添加 SENTENCE 列应该让事情变得更容易一些,但重要的是要注意,由于 df 中有数百个这样的句子,仅仅搜索索引“5”是行不通的,因为有数百行df['INDEX']=='5'.
这是我如何使用 get_head() 的示例:
def change_dependent(extract_col, extract_value, new_dependent_pos, head_pos):
name = 0
sub_df = df[df[extract_col] == extract_value] #this is another condition on the df.
for i, v in sub_df.iterrows():
if (get_head(df, v)['POS'] == head_pos):
df.at[v.name, 'POS'] = new_dependent_pos
return df
change_dependent('POS', 'ADV', 'ADV:VERB', 'VERB')
这里有人能想出一种更优雅/高效/熊猫的方式来获取所有头部为动词的 ADV 实例吗?
【问题讨论】:
标签: python pandas dataframe nlp