我是一个R语言用户,我无法找到pandas中match()函数的等效函数。我需要使用此函数遍历一堆文件,获取关键信息,并将其合并回“url”上的当前数据结构中。在R中,我会这样做:
logActions <- read.csv("data/logactions.csv")
logActions$class <- NA
files = dir("data/textContentClassified/")
for( i in 1:length(files)){
tmp <- read.csv(files[i])
logActions$class[match(logActions$url, tmp$url)] <-
tmp$class[match(tmp$url, logActions$url)]
}
我认为我不能使用merge()或join(),因为每次都会覆盖logActions$class。我也不能使用update()或combine_first(),因为它们都没有必要的索引功能。我还尝试了基于this SO post的match()函数,但无法弄清楚如何将其与DataFrame对象配合使用。如果我忽略了一些明显的东西,请原谅。
这里是一些Python代码,总结了我在pandas中无效尝试的一些操作:
from pandas import *
left = DataFrame({'url': ['foo.com', 'foo.com', 'bar.com'], 'action': [0, 1, 0]})
left["class"] = NaN
right1 = DataFrame({'url': ['foo.com'], 'class': [0]})
right2 = DataFrame({'url': ['bar.com'], 'class': [ 1]})
# Doesn't work:
left.join(right1, on='url')
merge(left, right, on='url')
# Also doesn't work the way I need it to:
left = left.combine_first(right1)
left = left.combine_first(right2)
left
# Also does something funky and doesn't really work the way match() does:
left = left.set_index('url', drop=False)
right1 = right1.set_index('url', drop=False)
right2 = right2.set_index('url', drop=False)
left = left.combine_first(right1)
left = left.combine_first(right2)
left
所需输出为:
url action class
0 foo.com 0 0
1 foo.com 1 0
2 bar.com 0 1
但是,我需要能够反复调用它,以便可以迭代每个文件。