【问题标题】:Fill new pandas df based off values in another df根据另一个df中的值填充新的pandas df
【发布时间】:2020-09-16 21:17:18
【问题描述】:

我是新来的,所以请不要对我太苛刻! :)

见下图!

我正在尝试根据 df['Datan'] 中的值创建一个新的数据框 (df['New_df']),以便在字符串 #SRU 出现的行上,df['New_df'] 等于 df['Datan']。如果字符串不在df['Datan'] 中,我希望df['New_df']“保留”上面行的值(其中包含#SRU 字符串)。

请参阅下面的 df 我正在尝试做的事情。

                                          Datan          New_df
                                 #SRU 1512 7251  #SRU 1512 7251
   #KONTO 1513 "Kundfordringar - delad faktura"  #SRU 1512 7251
                                 #SRU 1513 7251  #SRU 1513 7251
   #KONTO 1519 "Nedskrivning av kundfordringar"  #SRU 1513 7251
                                 #SRU 1519 7251  #SRU 1519 7251

我一直在尝试将 for 循环与 if 语句结合起来,特别是使用 apply 方法,但目前还没有找到解决方案。无法在此处的任何其他线程中找到此特定问题。

【问题讨论】:

    标签: python pandas loops dataframe if-statement


    【解决方案1】:

    使用,Series.str.containsSeries.mask & Series.ffill的组合:

    m = df['Datan'].str.contains(r'#SRU')
    df['New_df'] = df['Datan'].mask(~m).ffill()
    

    结果:

    # print(df)
                                              Datan          New_df
    0                                #SRU 1512 7251  #SRU 1512 7251
    1  #KONTO 1513 "Kundfordringar - delad faktura"  #SRU 1512 7251
    2                                #SRU 1513 7251  #SRU 1513 7251
    3  #KONTO 1519 "Nedskrivning av kundfordringar"  #SRU 1513 7251
    4                                #SRU 1519 7251  #SRU 1519 7251
    

    【讨论】:

      【解决方案2】:

      使用str.contains检查string是否匹配,然后使用ffill填充na

      df['New_df'] = df.Datan.where(df.Datan.str.contains('#SRU')).ffill()
      
      df
         Index                                           Datan            New_df
      0     95                                 #SRU 1512 7251    #SRU 1512 7251
      1     96   #KONTO 1513 "Kundfordringar - delad faktura"    #SRU 1512 7251
      2     97                                 #SRU 1513 7251    #SRU 1513 7251
      3     98   #KONTO 1519 "Nedskrivning av kundfordringar"    #SRU 1513 7251
      4     99                                 #SRU 1519 7251    #SRU 1519 7251
      

      【讨论】:

        猜你喜欢
        • 2020-12-29
        • 2017-04-22
        • 2020-08-16
        • 2022-06-10
        • 1970-01-01
        • 2017-06-22
        • 1970-01-01
        • 2020-04-06
        • 2021-03-25
        相关资源
        最近更新 更多