将 str 转换为 numpy 并加入 pandas 系列
Converting to str a numpy and join with pandas series
我需要帮助将一些随机整数和一些带前缀的 str 添加到 pandas 系列。我会更好地解释:
我有一个名为 variables 的 pandas 系列,我想向其中添加从 1 到 10 的随机整数以及一个加号和一个 space。
假设在我的 pandas 系列的给定行中,我有值 x1 并且我想向其添加(意味着连接)相应的值,假设 1,来自生成的随机数 numpy 数组,但也在中间放置一个 space 和一个 plus 在他们面前。
这是我想要获得的:
+1 x1
这是我所做的:
import numpy as np
coeff = np.random.randint(1, 11, variables.shape[0])
coeff = coeff.astype(str)
monom = '+' + coeff + ' ' + variables
但是它returns这个错误:
ufunc 'add' did not contain a loop with signature matching types (dtype('<U11'), dtype('<U11')) -> dtype('<U11')
有人知道如何帮助我吗?我也愿意改变这样做的方式,我只需要生成一些随机数但不一定需要传递给 numpy。
只需将coeff
转换成字符串Series:
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=' ')
我需要帮助将一些随机整数和一些带前缀的 str 添加到 pandas 系列。我会更好地解释: 我有一个名为 variables 的 pandas 系列,我想向其中添加从 1 到 10 的随机整数以及一个加号和一个 space。 假设在我的 pandas 系列的给定行中,我有值 x1 并且我想向其添加(意味着连接)相应的值,假设 1,来自生成的随机数 numpy 数组,但也在中间放置一个 space 和一个 plus 在他们面前。 这是我想要获得的:
+1 x1
这是我所做的:
import numpy as np
coeff = np.random.randint(1, 11, variables.shape[0])
coeff = coeff.astype(str)
monom = '+' + coeff + ' ' + variables
但是它returns这个错误:
ufunc 'add' did not contain a loop with signature matching types (dtype('<U11'), dtype('<U11')) -> dtype('<U11')
有人知道如何帮助我吗?我也愿意改变这样做的方式,我只需要生成一些随机数但不一定需要传递给 numpy。
只需将coeff
转换成字符串Series:
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=' ')