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

标签 python pandas loops dataframe if-statement

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

见下图!

Print screen: df['Datan]

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

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

                                          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.contains的组合, Series.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

关于python - 根据另一个 df 中的值填充新的 pandas df,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62083653/

相关文章:

r - 然后根据 R 中返回的新值匹配两列中的值

python - 如何在 pytest 中使用测试资源(如固定的 yaml 文件)?

python - 为什么我无法索引二维 numpy.ndarray 并分配新值

Python:将函数列表应用于列表中的每个元素

python - 重复同一行 Pandas Dataframe 构造

python - 如何获取从另一个模块调用的函数的结果对象?

loops - Rust:迭代 iter() 或向量本身

python - 使用Makefile bash保存python文件的内容

python - 带混合小数的列

javascript - 为什么这不起作用?在循环中调用属于对象的函数