Python中的清洗百分比列(小数+整数)有整数

Cleaning percentage column (decimal + whole number) in Python with whole number

我有一列百分比,其中包含像 0.4567 , 0.1564 , 19 , 23, 0 , 0.1234 这样的数字,我需要对整数进行归一化,即 45 , 15, 19 ,23 , 0 , 12 本身。我已经复制了一个例子如下。

import pandas as pd
import numpy as np
n_row =  10
dicti = {'id':[coli for coli in range(1,(n_row+1))],
     'perc_col':[30,0.4546,0.76543223190,10,0,0.29567,93,15,0.31,0.456]}
df = pd.DataFrame(dicti)
df

Data Frame Output

Expected Output

您可以标准化未标准化的数据框列并转换为整数(根据您的问题):

df['perc_col'] = df['perc_col'].apply(lambda x : int(x) if x > 1 else int(100*x))

输出

   id  perc_col
0   1        30
1   2        45
2   3        76
3   4        10
4   5         0
5   6        29
6   7        93
7   8        15
8   9        31
9  10        45

根据您的意见,如果您有 NaN 个值并希望保持不变,则不能将该列转换为 int。您可以将其保留为浮点数,但按如下方式更改为整数:

df['perc_col'] = df['perc_col'].apply(lambda x : x//1 if x > 1 else 100*x//1)

这次输出(将初始字典中的最后一个值改为np.nan)为:

   id  perc_col
0   1      30.0
1   2      45.0
2   3      76.0
3   4      10.0
4   5       0.0
5   6      29.0
6   7      93.0
7   8      15.0
8   9      31.0
9  10       NaN

为了满足处理字符串的第二个额外要求,如果将命令更改为:

,则基本上可以忽略字符串
df['perc_col'] = df['perc_col'].apply(lambda x : x if isinstance(x, str) else (x//1 if x > 1 else 100*x//1))