首页 > 解决方案 > 将系列放置到给定数组

问题描述

如何有效地将熊猫系列(或索引级别)放置到给定数组(系列,索引),x即将系列中的每个元素映射到地板数组中的最大元素y,这样y <= x

这是一个例子:

import pandas as pd

# the series
x = pd.Series([1.0, 1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.8, 9.9, 10.1, 11.11])

# the floor array
y = pd.Series([1.0, 4.0, 10.0])

# expected result (can be a numpy array, a Series, a list, etc...)
z = [1.0, 1.0, 1.0, 1.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 10.0, 10.0]

您可以假设系列和数组均按升序排序。

标签: pythonarrayspandasseriesfloor

解决方案


尝试pd.cut

pd.cut(x, bins=list(y)+[np.inf], right=False, labels=y).astype(float)

输出:

0      1.0
1      1.0
2      1.0
3      1.0
4      4.0
5      4.0
6      4.0
7      4.0
8      4.0
9      4.0
10    10.0
11    10.0
dtype: float64

推荐阅读