在Python中实现数值的2的幂值组合分解(对应R代码转译)
Python实现2的幂值分解(对应R代码逻辑)
以下是与你提供的R代码逻辑完全对齐的Python实现,使用pandas生成与R输出格式一致的结果:
import pandas as pd import math def to_codes(x): # 计算每个数值的最大2的幂次(log2向下取整) n_list = [math.floor(math.log2(num)) for num in x] max_n = max(n_list) # 生成从2^max_n到2^1的幂值序列 pow_values = [2**p for p in range(max_n, 0, -1)] # 构建二进制编码矩阵 y_matrix = [] for num in x: row = [(num // p) % 2 for p in pow_values] y_matrix.append(row) # 转换为DataFrame并过滤全0列 y_df = pd.DataFrame(y_matrix, columns=[f"code_{p}" for p in pow_values]) filtered_cols = y_df.any(axis=0) y_filtered = y_df.loc[:, filtered_cols] # 生成每个数值对应的2的幂组合字符串 possiblecodes = [] for row in y_matrix: selected_codes = [pow_values[i] for i, val in enumerate(row) if val == 1] possiblecodes.append(",".join(map(str, reversed(selected_codes)))) # 组合最终结果 result = pd.DataFrame({ "combinedvalue": x, "possiblecodes": possiblecodes }) result = pd.concat([result, y_filtered], axis=1) return result # 测试示例 x = [20, 50] print(to_codes(x))
输出结果
combinedvalue possiblecodes code_32 code_16 code_4 code_2 0 20 4,16 0 1 1 0 1 50 2,16,32 1 1 0 1
代码逻辑说明
- 确定幂次范围:通过计算每个输入值的
log2向下取整,得到需要处理的最大2的幂次; - 生成幂值序列:从最大幂次对应的2的幂开始,依次生成到2^1的序列;
- 二进制编码:对每个输入值,计算其在各个2的幂上的系数(0表示未使用该幂值,1表示使用);
- 过滤无效列:移除所有输入值都未使用的2的幂对应的列;
- 生成组合字符串:提取每个输入值用到的2的幂,反转后用逗号连接成字符串;
- 组合结果:将原始值、组合字符串和编码矩阵合并为最终的DataFrame。
内容的提问来源于stack exchange,提问作者Rajesh Addunuri
相关产品推荐
相关产品推荐

