【问题标题】:How to add rows based on a certain condition?如何根据特定条件添加行?
【发布时间】:2019-08-25 22:21:26
【问题描述】:

我正在尝试根据表中的商家 ID 添加 10 行。这是原始表 -

id    email    trend_type
1    abc@xyz.com 
2    cdsm@kcmd.com

这就是我想要创造的——

id    email    trend_type
1    abc@xyz.com   Bill 
1    abc@xyz.com   Visits
1    abc@xyz.com   Avg. Visits
1    abc@xyz.com   abc 
1    abc@xyz.com   mcd        
1    abc@xyz.com   mckfd      
1    abc@xyz.com   mfd        
1    abc@xyz.com   aps        
1    abc@xyz.com   mvmv       
1    abc@xyz.com   dep  
2    cdsm@kcmd.com Bill
2    cdsm@kcmd.com Visits    
.    .....         ...
.    .....         ...

我想将 10 种不同的趋势类型添加到一个 ID 和电子邮件组合中。我创建了所有趋势类型的数组,并尝试使用嵌套的 for 循环,但没有成功。真的可以使用一些帮助。

【问题讨论】:

    标签: python pandas data-cleaning


    【解决方案1】:

    使用Index.repeatDataFrame.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    abc@xyz.com         Bill
    0   1    abc@xyz.com       Visits
    0   1    abc@xyz.com  Avg. Visits
    0   1    abc@xyz.com          abc
    0   1    abc@xyz.com          mcd
    0   1    abc@xyz.com        mckfd
    0   1    abc@xyz.com          mfd
    0   1    abc@xyz.com          aps
    0   1    abc@xyz.com         mvmv
    0   1    abc@xyz.com          dep
    1   2  cdsm@kcmd.com         Bill
    1   2  cdsm@kcmd.com       Visits
    1   2  cdsm@kcmd.com  Avg. Visits
    1   2  cdsm@kcmd.com          abc
    1   2  cdsm@kcmd.com          mcd
    1   2  cdsm@kcmd.com        mckfd
    1   2  cdsm@kcmd.com          mfd
    1   2  cdsm@kcmd.com          aps
    1   2  cdsm@kcmd.com         mvmv
    1   2  cdsm@kcmd.com          dep
    

    【讨论】:

      【解决方案2】:

      productDataFrame.join 一起使用:

      from  itertools import product
      
      #add all types
      types = ['Bill','Visits','Avg. Visits']
      s = pd.DataFrame(list(product(df.index, types))).set_index(0)[1].rename('trend_type')
      df = df.join(s).reset_index(drop=True)
      print (df)
         id          email   trend_type
      0   1    abc@xyz.com         Bill
      1   1    abc@xyz.com       Visits
      2   1    abc@xyz.com  Avg. Visits
      3   2  cdsm@kcmd.com         Bill
      4   2  cdsm@kcmd.com       Visits
      5   2  cdsm@kcmd.com  Avg. Visits
      

      【讨论】:

        【解决方案3】:

        也许你可以使用那种东西:

        d = {'email':'blabla.bloblo@blublu.com',
            'trend_type':['bill','visits','abc', 'mcd', 'etc']}
        data = pd.DataFrame(d)
        

        您只需要在字典中添加更多条目并更新趋势列表 =)

        希望对你有帮助!

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-06-29
          • 1970-01-01
          • 2022-10-17
          • 2023-02-10
          • 2023-03-05
          • 2012-12-08
          相关资源
          最近更新 更多