Search code examples
pythonpandasdataframenumpyvectorization

How to cycle through values in Pandas Dataframe?


What's the fastest way to cycle through and repeat names in one dataframe when updating certain rows in a second dataframe? Thank you for your help. I've spent many days on this and am getting nowhere.

Rows with Rules 4,5,6,10,11,12 should cycle through and repeat names in the Names Dataframe.

This is the dataframe I want to change:

Rule Name
12 Nan
9 Nan
7 Nan
1 Nan
3 Nan
2 Nan
4 Nan
6 Nan
9 Nan
4 Nan
1 Nan
4 Nan
5 Nan
2 Nan
11 Nan
6 Nan
9 Nan
2 Nan
10 Nan
3 Nan
10 Nan
3 Nan
1 Nan
4 Nan
4 Nan
3 Nan
7 Nan
7 Nan
12 Nan

This is the result I am trying to achieve:

Rule Name
12 Adams
9 Nan
7 Nan
1 Nan
3 Nan
2 Nan
4 Baker
6 Clark
9 Nan
4 Davis
1 Nan
4 Adams
5 Baker
2 Nan
11 Clark
6 Davis
9 Nan
2 Nan
10 Adams
3 Nan
10 Baker
3 Nan
1 Nan
4 Clark
4 Davis
3 Nan
7 Nan
7 Nan
12 Adams

Name Dataframe

Name
Adams
Baker
Clark
Davis

I tried to numpy vectorize, but only got one name for all the entries that I wanted to change.


Solution

  • IIUC, you can

    1. check if each element of df1 Rule column isin your rule list.
    2. Then cycle through and repeat names of df2 Name column depending on the length of the contained rule.
    3. At last conditionally assign the repeat names to df1 Rule column.
    lst = [4,5,6,10,11,12]
    m = df1['Rule'].isin(lst)
    df1.loc[m, 'Name'] = (df2['Name'].tolist() * (m.sum()//len(df2['Name']) + 1))[:m.sum()]
    
    print(df1)
    
        Rule   Name
    0     12  Adams
    1      9    Nan
    2      7    Nan
    3      1    Nan
    4      3    Nan
    5      2    Nan
    6      4  Baker
    7      6  Clark
    8      9    Nan
    9      4  Davis
    10     1    Nan
    11     4  Adams
    12     5  Baker
    13     2    Nan
    14    11  Clark
    15     6  Davis
    16     9    Nan
    17     2    Nan
    18    10  Adams
    19     3    Nan
    20    10  Baker
    21     3    Nan
    22     1    Nan
    23     4  Clark
    24     4  Davis
    25     3    Nan
    26     7    Nan
    27     7    Nan
    28    12  Adams