繁体   English   中英

根据另一个df中的值填充新的pandas df

[英]Fill new pandas df based off values in another df

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

见下图!

打印屏幕:df['Datan]

我正在尝试根据 df['Datan'] 中的值创建一个新的 dataframe ( df['New_df'] df['Datan'] ,以便df['New_df']在字符串所在的行上等于df['Datan'] ['Datan'] #SRU出现。 如果字符串不在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 方法,但到目前为止还没有找到解决方案。 无法在此处的任何其他线程中找到此特定问题。

使用Series.str.containsSeries.maskSeries.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

使用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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM