Skip to main content
 首页 » 编程设计

python之在 python 中从 R 转换

2025年05月04日21虾米哥

我正在将 R 代码转换为 Python。我知道存在从 python 调用 R 的替代方法,但是,我需要将它逐行转换为 python。

我在 R 代码中有一行是
reps[-a] <- .Machine$integer.max
其中 reps 是一个向量,a 是另一个包含一些索引的向量,例如 一 = [1, 2, 4]

我想知道如何在 python 中实现这一行。
据我了解,它应该将最大值分配给数组中索引不等于 1,2 或 4 的所有元素。

谢谢。

请您参考如下方法:

R的原子向量/矩阵/数组最好的翻译是Python的numpy N-D array和 .Machine$integer.max 将转换为 numpy dtype 的最大 int32 值。

但是,numpy 数组没有简单的索引定位器,因此需要更长的路径,如 @mglison 所示。使用 bool 掩码:

a = np.array([1, 3, 4, 6, 79, 10, 56])     
b = np.array([0, 1, 2]) 
 
mask = mask = np.full(a.shape, False) 
mask[b] = True 
a[~mask] = np.iinfo(np.int32).max 
 
a 
# array([         1,          3,          4, 2147483647, 2147483647, 
#    2147483647, 2147483647]) 

或者,Python 的 pandas Series是 numpy 一维数组的扩展,但需要索引对齐:

a = pd.Series([1, 3, 4, 6, 79, 10, 56]) 
b = pd.Series([0, 1, 2]) 
 
a[~a.index.isin(b)] = np.iinfo(np.int32).max 
 
# 0             1 
# 1             3 
# 2             4 
# 3    2147483647 
# 4    2147483647 
# 5    2147483647 
# 6    2147483647 
# dtype: int64