【问题标题】:Converting to str a numpy and join with pandas series转换为 str a numpy 并加入 pandas 系列
【发布时间】:2021-03-27 01:44:03
【问题描述】:

我需要帮助将一些随机整数和一些前缀 str 添加到 pandas 系列。我最好解释一下: 我有一个名为 variables 的 pandas 系列,并想在其中添加从 1 到 10 的随机整数以及一个加号和一个空格。 假设在我的熊猫系列的给定行中,我有值 x1,我想向它添加(意味着加入)相应的值,比如说 1,从生成的 numpy 随机数数组中提取,但在它们之间放置一个 空格,在它们之前放置一个 加号。 这是我想要获得的:

+1 x1

这就是我所做的:

import numpy as np
coeff = np.random.randint(1, 11, variables.shape[0])
coeff = coeff.astype(str)
monom = '+' + coeff + ' ' + variables

但它返回此错误:

ufunc 'add' did not contain a loop with signature matching types (dtype('<U11'), dtype('<U11')) -> dtype('<U11')

有人知道如何帮助我吗?我也愿意改变这样做的方式,我只需要生成一些随机数,但不一定需要传递给 numpy。

【问题讨论】:

    标签: pandas string numpy join numpy-ufunc


    【解决方案1】:

    只需将coeff 转换为字符串系列:

    import pandas as pd
    import numpy as np
    
    # dummy series for setup
    variables = pd.Series(list('abcde'))
    
    # create new random Series
    coeff = pd.Series(np.random.randint(1, 11, variables.shape[0]), dtype=str)
    
    # add
    monom = '+' + coeff + ' ' + variables.astype(str)
    
    print(monom)
    

    输出

    0     +8 a
    1     +2 b
    2    +10 c
    3     +3 d
    4     +8 e
    dtype: string
    

    您也可以使用str.cat 方法:

    monom = '+' + coeff.str.cat(variables.astype(str), sep=' ')
    

    【讨论】:

      猜你喜欢
      • 2018-07-25
      • 2016-08-26
      • 2020-09-02
      • 1970-01-01
      • 2022-10-15
      • 2014-12-19
      • 2015-12-01
      • 2019-05-05
      • 1970-01-01
      相关资源
      最近更新 更多