Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Pandas 转换为str a numpy并加入熊猫系列_Pandas_String_Numpy_Join_Numpy Ufunc - Fatal编程技术网

Pandas 转换为str a numpy并加入熊猫系列

Pandas 转换为str a numpy并加入熊猫系列,pandas,string,numpy,join,numpy-ufunc,Pandas,String,Numpy,Join,Numpy Ufunc,我需要帮助添加一些随机整数和一些前缀str到熊猫系列。我最好解释一下: 我有一个名为variables的pandas系列,我想给它添加1到10的随机整数,还有一个加号和一个空格。 假设在我的pandas系列的给定行中,我有一个值x1,我想从一个生成的随机数numpy数组中,向它添加相应的值,比如说1,但在它们之间加一个空格,在它们前面加一个加号。 这就是我想要得到的: +1 x1 这就是我所做的: import numpy as np coeff = np.random.randint(1,

我需要帮助添加一些随机整数和一些前缀str到熊猫系列。我最好解释一下: 我有一个名为variables的pandas系列,我想给它添加1到10的随机整数,还有一个加号和一个空格。 假设在我的pandas系列的给定行中,我有一个值x1,我想从一个生成的随机数numpy数组中,向它添加相应的值,比如说1,但在它们之间加一个空格,在它们前面加一个加号。 这就是我想要得到的:

+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。

只要将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
monom = '+' + coeff.str.cat(variables.astype(str), sep=' ')