python - python Pandas/numpy 的 R 的 match() 等价物是什么?

标签 python r merge pandas match

我是一名 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 中尝试做类似 match() 的无效尝试:

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

但是,我需要能够一遍又一遍地调用它,以便遍历每个文件。

最佳答案

请注意 pandas.match 的存在,它所做的正是 R 的 match 所做的。

关于python - python Pandas/numpy 的 R 的 match() 等价物是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15856213/

相关文章:

rmarkdown 内联代码与代码块

json - 如何以更简洁的方式将 JSON 格式的请求从 R 中的 URL 获取 JSON 数据发送到 data.frame 中?

r - 如何从数据帧列表中添加单个数据帧

python - 使用 Python 将两个 CSV 文件与案例合并

python - 在 azure 存储上创建连接时如何处理错误

python - 哪个更好-execute(INSERT) 或executemany(INSERT)

r - 如何在 `data.table`中加入有最小数据量的条件来计算一个变量

python - 选择重复出现的值

Python 数据帧 : issue when attempting to group by multiple columns

Git merge 提交未在 Git/SourceTree 中显示为 merge