如何对此进行矢量化?

时间:2015-11-19 09:29:55

标签: python numpy

我正在寻找矢量化的方法:

for x in range(1,N+1):
  mul3ou5 = "inf"*(x%3 == 0)+"luans"*(x%5==0) 
  print str(x)*(mul3ou5 =="")+mul3ou5

想法是使用numpy数组并在numpy数组numpy.array(range(100))

上用一个操作替换for循环

提前致谢

3 个答案:

答案 0 :(得分:2)

虽然@ morningsun的答案很棒,但另一个选择是(使用boolean indexing):

import numpy as np

x = np.arange(1, N+1)
s = x.astype('S8')
s[x % 3 == 0] = 'inf'
s[x % 5 == 0] = 'luans'
s[x % 15 == 0] = 'influans'

我发现它更直观,因为它保留了显式模数(%)操作。

答案 1 :(得分:1)

可以使用pandas

import pandas as pd
# generating data set (N: number, S: resulting string)
df = pd.DataFrame({'N': np.arange(1,N+1), 'S': np.arange(1,N+1) },columns=['N','S'])
# convert col. S to string
df['S']=df['S'].apply(str)
# set empty string if x mod 3 == 0 or x mod 5 == 0
df['S'][(df['N'].mod(3)==0) | (df['N'].mod(5)==0)] = ""
# set mod 3 == 0 condition
df['S'][(df['N'].mod(3)==0)] = "inf"
# mod 5 == 0
df['S'][(df['N'].mod(5)==0)] = df['S']+"luans"

结果位于df['S']

答案 2 :(得分:1)

分配给切片:

S = numpy.arange(1, N+1).astype('S8')
S[2::3] = 'inf'
S[4::5] = 'luans'
S[14::15] = 'influans'