Python 使用 splat 运算符创建具有未知数字参数的函数

Python Creating a function with unkown number arguments with splat operator

我正在尝试对数据框中的数字进行舍入,该数据框中的每一行都有列表作为值。我需要整数没有小数点,浮点数在小数点后只有两位。每个列表的值数量未知(有些列表有 2 个值,有些有 4 个或 5 个或更多)。这是我拥有的:

df = pd.DataFrame({"A": [[16.0, 24.4175], [14.9687, 16.06], [22.75, 23.00]]})

def remove_exponent(num):
    return num.to_integral() if num == num.to_integral() else num.normalize()

def round_string_float(x):
    try:
        return remove_exponent(Decimal(x).quantize(TWOPLACES))
    except:
        return x  
df['A']=df['A'].apply(lambda x: [round_string_float(num) for num in x])
But this gives me: [Decimal('16'), Decimal('24.42')]

这是我正在尝试的:

def round(num):
     if str(numbers).find('/') > -1:
          nom, den = numbers.split(',')
          number=round_string_float(nom)
          second=round_string_float(den)
          return f'[{number}, {second}]'
but there has to be an easier way to do this

这是我想要的:

df = pd.DataFrame({"A": [[16, 24.42], [14.97, 16.06], [22.75, 23]]})

我想知道必须使用 **args 来执行此操作,但实际上任何有用的东西都会很好

你试过for循环了吗?例如

list = []
for i in range(len(df)):
    for j in range(len(df[i])):
        list .append(round(df[i][j]))

这是一种奇怪的 DataFrame 格式,但如果你想要它,你可以这样做:

import pandas as pd

df = pd.DataFrame({"A": [[16.0, 24.4175], [14.9687, 16.06], [22.75, 23.00]]})
print(df.applymap(lambda x: [round(v, None if v.is_integer() else 2) for v in x]))

Given that

The return value [of round] is an integer if ndigits is omitted or None.

对于每个嵌套数字 v,如果 v 是整数,则 round(v) 计算其他 round(v, 2)

这输出

                A
0     [16, 24.42]
1  [14.97, 16.06]
2     [22.75, 23]

我为这个问题创建了一个超出我想要的答案,但我认为它会帮助任何寻找类似东西的人。我公司的问题是我们必须将列表作为数据框中的值上传到数据库。这就是代码如此特别的原因:

from decimal import *
TWOPLACES = Decimal(10) ** -2
from natsort import natsorted
import ast
from fractions import Fraction
#----------------------------------------------------------------
# remove_exponent and round string float are designed to round whole numbers 16.00 to 16, and rounds numbers with 3 or more decimals to 2 decimals 16.254 to 16.25
def remove_exponent(num): 
    return num.to_integral() if num == num.to_integral() else num.normalize()

def round_string_float(x):
    try:
        return remove_exponent(Decimal(x).quantize(TWOPLACES))
    except:
        return x 
#------------------------------------------------------------------------------
# frac2string converts fractions to decimals: 1 1/2 to 1.5
def frac2string(s):
    i, f = s.groups(0)
    f = round_string_float(Fraction(f))
    return str(int(i) + round_string_float(float(f)))

#------------------------------------------
#remove duplicates is self explanitory
def remove_duplicates(A):
    [A.pop(count) for count,elem in enumerate(A) if A.count(elem)!=1]
    return A


# converts fractions and rounds numbers
df['matches'] = df['matches'].apply(lambda x:[re.sub(r'(?:(\d+)[-\s])?(\d+/\d+)', frac2string, x)])

# removes duplicates( this needs to be in the format ["\d","\d"]
df['matches'] = df['matches'].apply(lambda x: remove_duplicates([n.strip() for n in ast.literal_eval(x)]))