我想从此符号列表中随机选择一个字符串而不替换:'@','+','?','!','$','*','%','#', '}','>','&','^'。
生成的字符串的长度将等于csv中另一列中的单词的长度。
现有csv的示例:
Word Length
dog 3
wolf 4
cactus 6
bus 3
我想拥有这样的代码,使其将第三列附加到现有的csv文件中,并且每个单词的生成字符串的长度相等。这是我想要的结果的一个示例:
Word Length String
dog 3 @!#
wolf 4 &*%!
cactus 6 ^?!@#%
bus 3 }&^
这是我尝试过的代码,但我认为这是不对的。
import random
import pandas as pd
import os
cwd = os.getcwd()
cwd
os.chdir("/Users/etcetc") #change directory
df = pd.read_csv('generatingstring.csv')
list1 = ['@','+','?','!','$','*','%','#','}','>','&','^']
list2 = df['String'] #creating a new column for the generated string
for row in df['Length']: #hope this reads each row in that column
for n in range(1, row): #hope this reads the length value within cell
s = random.choice(list1)
list1.remove(s) #to ensure random selection without replacement
list2.append(s)
我希望让它读取“长度”列中的每一行,并在每一行中记下要随机选择的符号数。
谢谢!
你可以试试
import numpy as np
df.Word.map(lambda x : ''.join(np.random.choice(list1,len(x),replace = False)))
Out[145]:
0 &$!
1 >^$!
2 @}%?$>
3 #+!
Name: Word, dtype: object
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句