lundi 4 juin 2018

Python: looping through dataframe and generating random int

I have a lookup dataframe as follows:

            String   Length
0            A       2
1            B       4
2            C       3
3            D       2

I have an input dataframe as follows:

   Input
0  A20
1  B1611
2  C001
3  D18

I want to get an output like:

      Output
    0  C300
    1  B2718
    2  C421
    3  A17

Where B2718 is B concatenated with a random value 2718 which is a 4 digit int, and the length 4 is obtained from "Length" column of lookup.

I have written the following code:

def random_with_N_digits(n):
    range_start = 10**(n-1)
    range_end = (10**n)-1
    return randint(range_start, range_end)

for index, row in lookup.iterrows():
    r_int = random_with_N_digits(row.Length)
    data = row.String+str(r_int)
    r_df = pd.read_fwf(io.StringIO(data), header=None)

But I'm unable to get an output dataframe (r_df) of the same size as input dataframe.

Please suggest.




Aucun commentaire:

Enregistrer un commentaire