Search code examples
pythonpandasdata-cleaning

How to add rows based on a certain condition?


I'm trying to add 10 rows based on a merchant_id in a table. This is the original table -

id    email    trend_type
1    [email protected] 
2    [email protected]

And this is what I'm trying to create -

id    email    trend_type
1    [email protected]   Bill 
1    [email protected]   Visits
1    [email protected]   Avg. Visits
1    [email protected]   abc 
1    [email protected]   mcd        
1    [email protected]   mckfd      
1    [email protected]   mfd        
1    [email protected]   aps        
1    [email protected]   mvmv       
1    [email protected]   dep  
2    [email protected] Bill
2    [email protected] Visits    
.    .....         ...
.    .....         ...

I have 10 different trend types that I want to add to one id and email combination. I've created an array of all the trend types and I've tried using a nested for loop but I haven't been successful. Could really use some help.


Solution

  • Use Index.repeat and DataFrame.assign:

    trends = ['Bill','Visits', 'Avg. Visits','abc',
              'mcd', 'mckfd', 'mfd', 'aps', 'mvmv', 'dep']
    
    df_new = df.loc[df.index.repeat(len(trends))].assign(trend_type=trends * len(df))
    print(df_new)
    
       id          email   trend_type
    0   1    [email protected]         Bill
    0   1    [email protected]       Visits
    0   1    [email protected]  Avg. Visits
    0   1    [email protected]          abc
    0   1    [email protected]          mcd
    0   1    [email protected]        mckfd
    0   1    [email protected]          mfd
    0   1    [email protected]          aps
    0   1    [email protected]         mvmv
    0   1    [email protected]          dep
    1   2  [email protected]         Bill
    1   2  [email protected]       Visits
    1   2  [email protected]  Avg. Visits
    1   2  [email protected]          abc
    1   2  [email protected]          mcd
    1   2  [email protected]        mckfd
    1   2  [email protected]          mfd
    1   2  [email protected]          aps
    1   2  [email protected]         mvmv
    1   2  [email protected]          dep