给定两个具有相同列的DataFrame.

DFA

Index Price
0     10.21
1     12.21

DFB

Index Price
0     10.21
1     10.24
2     11.32
3     12.21

I want to add a column to DFA with the times that each value appears in DFB, but with a tolerance of, let's say, 1%.

结果

Index Price Occurrences 
0     10.21 2
1     12.21 1

是否仍有可能避免迭代?也许用merge_asofgrouping

附注:这是对我的其他question条的修正,但发布了不同的威胁,因为它涉及的是一个略有不同的问题.

推荐答案

As you want to test all combinations, use broadcasting:

a = dfA['Price'].to_numpy()[:,None]
b = dfB['Price'].to_numpy()

dfA['Occurrences'] = (abs(a-b) < a*0.01).sum(axis=1)

输出:

   Index  Price  Occurrences
0      0  10.21            2
1      1  12.21            1

中间体:

# abs(a-b)
array([[0.  , 0.03, 1.11, 2.  ],
       [2.  , 1.97, 0.89, 0.  ]])

# (abs(a-b) < a*0.01)
array([[ True,  True, False, False],
       [False, False, False,  True]])

Python相关问答推荐

如何将Pydantic URL验证限制为特定主机或网站

从多行文本中提取事件对

在Docker中运行HAProxy时无法获得503服务

在for循环中仅执行一次此操作

Python plt.text中重叠,包adjust_text不起作用,如何修复?

Python在tuple上操作不会通过整个单词匹配

我从带有langchain的mongoDB中的vector serch获得一个空数组

连接两个具有不同标题的收件箱

韦尔福德方差与Numpy方差不同

滚动和,句号来自Pandas列

Pandas 都是(),但有一个门槛

如何使用LangChain和AzureOpenAI在Python中解决AttribeHelp和BadPressMessage错误?

在Polars(Python库)中将二进制转换为具有非UTF-8字符的字符串变量

Telethon加入私有频道

使用setuptools pyproject.toml和自定义目录树构建PyPi包

Streamlit应用程序中的Plotly条形图中未正确显示Y轴刻度

当点击tkinter菜单而不是菜单选项时,如何执行命令?

如何在FastAPI中为我上传的json文件提供索引ID?

在方法中设置属性值时,如何处理语句不可达[Unreacable]";的问题?

OpenCV轮廓.很难找到给定图像的所需轮廓