1

I would like to randomly select a string of characters from this list of symbols without replacement: '@','+','?','!','$','*','%','#','}','>','&','^'.

The length of the generated string would be equal in length to the word in another column from the csv.

Example of an existing csv:

Word     Length
dog      3
wolf     4
cactus   6
bus      3

I would like to have the code such that it appends a third column to the existing csv file with the generated string equal in length for each word. This is an example of the result I want:

Word     Length     String
dog      3          @!#
wolf     4          &*%!
cactus   6          ^?!@#%
bus      3          }&^

This is the code I tried but I do not think it is right.

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)

I was hoping to make it read each row within the Length column, and within each row take note of how many symbols to randomly select.

Thank you!

2
  • you don't need the second loop if you use numpy, see the replace=False argument in [np.random.choice] Commented Aug 17, 2020 at 15:12
  • Does this answer your question? Weighted random sample without replacement in python Commented Aug 17, 2020 at 15:14

1 Answer 1

1

You can try

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
Sign up to request clarification or add additional context in comments.

2 Comments

This works! I am also curious, how do I append this output into a brand new column in my existing csv? Thank you so much!
Apologies @BEN_YO, when I did output.to_csv(filename, mode='a', header='Symbols', index =False), the symbol string did not append to a new column. Instead, it attached below the word column. How can I save it properly?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.