pandas 在Python中查找给定列的所有2幂值组合值的总和

m4pnthwp  于 2023-05-12  发布在  Python
关注(0)|答案(1)|浏览(211)

Dataframe 1:
| 联系方式|幂值|
| --------------|--------------|
| 0| 1|
| 1|二|
| 二|四个|
| 三|八|
| 四个|十六岁|
| 五|三十二|
Dataframe 2:
| 组合值|
| --------------|
| 二十|
| 五十|
Stack Overflow上的某个人提供了以下R代码。
Finding all sum of 2 power value combination values of a given number in R
我在Python中寻找相同的代码。

toCodes <- function(x) {
  n <- floor(log2(x))
  pow <- rev(seq.int(max(n)))
  # 'y' is the matrix of codes
  y <- t(sapply(x, \(.x) (.x %/% 2^pow) %% 2L))
  i_cols <- apply(y, 2, \(.y) any(.y != 0L))
  colnames(y) <- sprintf("code_%d", 2^pow)
  #
  possiblecodes <- apply(y, 1, \(p) {
    codes <- 2^pow[as.logical(p)]
    paste(rev(codes), collapse = ",")
  })
  data.frame(combinedvalue = x, possiblecodes, y[, i_cols])
}

x <- c(20L, 50L)
toCodes(x)
lc8prwob

lc8prwob1#

import pandas as pd
import numpy as np

def to_codes(x):
    n = np.floor(np.log2(x))
    pow_ = np.flip(np.arange(n + 1))
    # 'y' is the matrix of codes
    y = np.transpose(np.array([np.floor(x / 2**pow_) % 2 for x in x]))
    i_cols = np.apply_along_axis(lambda y: np.any(y != 0), 0, y)
    colnames = ["code_" + str(int(2**pow)) for pow in pow_]
    #
    possiblecodes = np.apply_along_axis(lambda p: ",".join([str(int(codes)) for codes in np.flip(pow_[np.where(p > 0)])]), 1, y)
    return pd.DataFrame({"combinedvalue": x, "possiblecodes": possiblecodes, **{colnames[i]: y[:, i] for i in np.where(i_cols)}})

调用to_codes的函数,该函数接受整数x的数组作为输入,并返回具有三列的pandas DataFrame:combinedvalue、possiblecodes和一组标为code_2^n的列,其中n是2的幂。

相关问题