【问题标题】:Replace each value of string appearing in pandas dataframe with separate floating value用单独的浮点值替换出现在熊猫数据框中的字符串的每个值
【发布时间】:2021-01-09 21:06:29
【问题描述】:

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

输入数据框:

   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-60 千行。所以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)

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

【问题讨论】:

    标签: python pandas numpy


    【解决方案1】:

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

    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
    )
    

    【讨论】:

    • 如果我用四个数字代替字符串来表示 l、m、h、c 怎么办?
    • 嗯,这大大简化了它。您可以为此发布一个新问题吗? @mss
    【解决方案2】:

    我们试试吧:

    s = df.stack()
    
    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))
    
    
    s.groupby(s).transform(get_rand).unstack()
    

    输出:

              A         B         C
    0  0.351150  0.673156  0.829484
    1  0.095481  0.836520  0.258559
    2  0.599817  0.282766  0.048788
    3  0.851617  0.010585  0.501335
    4  0.422449  0.997759  0.287950
    

    【讨论】:

      【解决方案3】:

      可以试试

      out = df.applymap(lambda x : np.random.uniform(*ranges[x],1)[0])
                A         B         C
      0  0.399545  0.592302  0.862708
      1  0.135859  0.873516  0.381962
      2  0.665365  0.410010  0.127253
      3  0.936032  0.241266  0.686508
      4  0.273130  0.839988  0.391465
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-05-09
        • 1970-01-01
        • 1970-01-01
        • 2020-03-07
        • 2014-10-31
        • 2018-01-02
        • 2021-09-07
        相关资源
        最近更新 更多