代码之家  ›  专栏  ›  技术社区  ›  levant pied

Pandas连接字符串和numpy数组

  •  1
  • levant pied  · 技术社区  · 3 年前

    我有这个:

    n = 5                                            
    df = pandas.DataFrame(dict(j=numpy.repeat(0, n)))
    df['j'] = 'prefix-'                              
    df['j'] += numpy.arange(n).astype('U')           
    df['j'] += '-suffix'                             
    print(df)                                        
    

    其产生:

                     j
    0  prefix-0-suffix
    1  prefix-1-suffix
    2  prefix-2-suffix
    3  prefix-3-suffix
    4  prefix-4-suffix
    

    有没有办法在一行中(合理地)做到这一点?

    我试过:

    df['j'] = 'prefix-' + numpy.arange(n).astype('U') + '-suffix'
    

    但这导致了这个错误:

    numpy.core._exceptions._UFuncNoLoopError: ufunc 'add' did not contain a loop with signature matching types (dtype('<U7'), dtype('<U21')) -> None
    
    2 回复  |  直到 3 年前
        1
  •  4
  •   Corralien    3 年前

    使用转换为字符串 astype 和 pd.RangeIndex

    # df['j'] = 'prefix-' + df['j'].astype(str) + '-suffix'
    df['j'] = 'prefix-' + pd.RangeIndex(n).astype(str) + '-suffix'
    print(df)
    
    # Output
                     j
    0  prefix-0-suffix
    1  prefix-1-suffix
    2  prefix-2-suffix
    3  prefix-3-suffix
    4  prefix-4-suffix
    
        2
  •  1
  •   constantstranger    3 年前

    假设有一个你想使用的原因 numpy.arange(n).astype('U') ,您可以将此调用包装在一个系列中:

    df['j'] = 'prefix-' + pandas.Series(numpy.arange(n).astype('U'), index=df.index) + '-suffix'
    

    如果目标只是获得最终结果,那么您可以在 n = 5 到df的单行初始化:

    df = pandas.DataFrame({'j': 'prefix-' + pandas.Series(range(n)).astype(str) + '-suffix'})