我是新来的,所以请不要对我太苛刻! :)
见下图!
我正在尝试根据 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/