首页 > 解决方案 > 用单独的浮点值替换出现在熊猫数据框中的每个字符串值

问题描述

我有一个看起来像这样的熊猫数据框:

输入数据框:

   A    B   C 
0   m   h   c 
1   l   c   m 
2   h   m   l 
3   c   l   h 
4   m   c   m

我想用给定范围内的浮点数替换每个l、m、h 和 c值的每次出现。每个字符串的取值范围如下:

范围:

l: 0.0  - 0.25
m: 0.25 - 0.5
h: 0.5  - 0.75
c: 0.75 - 1.0

每次出现都应具有给定范围内的值,但不应重复。转换后的示例输出数据框应如下所示:

输出数据框:

       A       B      C
 0  0.31    0.51    0.76
 1  0.12    0.56    0.28
 2  0.61    0.35    0.21
 3  0.8     0.16    0.71
 4  0.46    0.72    0.37

我尝试了一种使用transform. 但它不能完全工作,因为值在列中重复:

def _foo(col):
    w = {'l': np.random.uniform(0.0,0.25),
            'm':np.random.uniform(0.25,0.5),
            'h': np.random.uniform(0.5,0.75), 
            'c':np.random.uniform(0.75,1.0)}
    col = col.replace(w)
    return col

df = df.transform(_foo)

如果我使用apply方法,那么也会发生同样的问题,并且值会沿行重复。它也没有很好的性能,因为实际的数据帧有 50-60000 行。所以apply会运行很多次。

def _bar(row):
        w = {'l': np.random.uniform(0.0,0.25),
                'm':np.random.uniform(0.25,0.5),
                'h': np.random.uniform(0.5,0.75), 
                'c':np.random.uniform(0.75,1.0)}
        row= row.replace(w)
        return row
    
 df = df.apply(_bar, axis=1)

关于如何在熊猫中有效地做到这一点有什么建议吗?

标签: pythonpandasnumpy

解决方案


这是一种针对性能的矢量化方法:

def map_by_val(df, l):
    # dictionary to map dataframe values to index
    d = {j:i for i,j in enumerate(l)}
    # replace using dictionary
    a = df.replace(d).to_numpy()
    # since the ranges are a sequence, we can create a 
    # linspace, and divide in 10 bins each range
    rep = np.linspace(0.0, 1.0, 40).reshape(4,-1)
    # random integer indexing in each rows
    ix = np.random.randint(0,rep.shape[1],a.shape)
    # advanced indexing of the array using random integers per row
    out = rep[a.ravel(), ix.ravel()].reshape(a.shape).round(2)
    return pd.DataFrame(out)

l = ['l','m','h','c']
map_by_val(df, l)

      0     1     2
0  0.49  0.74  0.87
1  0.23  0.90  0.49
2  0.67  0.49  0.18
3  0.79  0.21  0.56
4  0.46  0.87  0.36

基准

不幸的是,该对象dtype限制了矢量化方法的性能,因为最初DataFrame.replace调用该对象以使用字典映射值。这个答案和stack+groupby答案的表现都非常相似:

l = ['l','m','h','c']

ranges = {'l': (0,0.25),
          'm': (0.25, 0.5),
          'h': (0.5,0.75),
          'c':(0.75,1)}

def get_rand(x):
    lower, upper = ranges[x.iloc[0]]
    return np.random.uniform(lower, upper, len(x))

def stack_groupby(df):
    s = df.stack()
    return s.groupby(s).transform(get_rand).unstack()

plt.figure(figsize=(12,6))

perfplot.show(
    setup=lambda n: pd.concat([df]*n, axis=0).reset_index(drop=True), 

    kernels=[
        lambda s: s.applymap(lambda x : np.random.uniform(*ranges[x],1)[0]),
        lambda s: map_by_val(s, l),
        lambda s: stack_groupby(s)
    ],

    labels=['applymap', 'map_by_val', 'stack_groupby'],
    n_range=[2**k for k in range(0, 17)],
    xlabel='N',
    equality_check=None
)

在此处输入图像描述


推荐阅读