创建一个可以删除字符和乘以数字的函数

Create a function that can remove characters and multiply figures

我需要构建一个名为 format_adjustment 的函数,它可以删除“%”字符,并将任何大于 0 的值乘以 100。(此外,任何负值保持不变)。

示例数据集:

df = pd.DataFrame({'col1': ['A','B','C'], 'col2':[-0.42%,0.091,0.0023%], 'col3': [30, 10,20]})

   col1     col2   col3
0     A   -0.42%     30
1     B    0.091     10
2     C  0.0023%     20

col2 的预期结果如下:

df = pd.DataFrame({'col1': ['A','B','C'], 'col2':[-0.42,0.091,0.0023], 'col3': [30, 10,20]})

   col1     col2   col3
0     A    -0.42     30
1     B      9.1     10
2     C     0.23     20
df['col2'] = df['col2'].astype('str').str.replace('%', '').astype('float')
df['col2'] *= np.where(df['col2'] > 0, 100, 1)

输出:

>>> df
  col1  col2  col3
0    A -0.42    30
1    B  9.10    10
2    C  0.23    20
def format_adjustment(col2):
    # remove % and convert to float
    col2 = float(col2.replace('%', ''))
    # multiply by 100 if > 0
    if col2 > 0:
         col2 *= 100
    return col2

df = pd.DataFrame({'col1': ['A','B','C'], 'col2':['-0.42%','0.091','0.0023%'], 'col3': [30, 10,20]})
# apply format_adjustment function
df['col2'] = df['col2'].apply(lambda x: format_adjustment(x))

输出:

>>> df
  col1  col2  col3
0    A -0.42    30
1    B  9.10    10
2    C  0.23    20