我试图通过使用str.contains()
和np.where()
函数提供多个包含条件的字符串来添加一个新列。这样,我就可以得到我想要的最终结果。你知道吗
但是,代码非常长。有没有什么好方法可以使用pandas函数重新实现这个功能?你知道吗
df5['new_column'] = np.where(df5['sr_description'].str.contains('gross to net', case=False).fillna(False),1,
np.where(df5['sr_description'].str.contains('gross up', case=False).fillna(False),1,
np.where(df5['sr_description'].str.contains('net to gross',case=False).fillna(False),1,
np.where(df5['sr_description'].str.contains('gross-to-net',case=False).fillna(False),1,
np.where(df5['sr_description'].str.contains('gross-up',case=False).fillna(False),1,
np.where(df5['sr_description'].str.contains('net-to-gross',case=False).fillna(False),1,
np.where(df5['sr_description'].str.contains('gross 2 net',case=False).fillna(False),1,
np.where(df5['sr_description'].str.contains('net 2 gross',case=False).fillna(False),1,
np.where(df5['sr_description'].str.contains('gross net',case=False).fillna(False),1,
np.where(df5['sr_description'].str.contains('net gross',case=False).fillna(False),1,
np.where(df5['sr_description'].str.contains('memo code',case=False).fillna(False),1,0)))))))))))
这个输出将是
如果这些字符串包含在'sr\u description'中,则给出1
,否则0
到new_column
可以将多个字符串条件存储在一个列表中,然后读取并应用到函数中。你知道吗
编辑:
样本数据:
sr_description new_column
something with gross up. 1
without those words. 0
or with Net to gross 1
if not then we give a '0' 0
这是我想到的。你知道吗
代码:
结果:
注意,
numpy
不是解决方案运行所必需的,我只是用它来测试NaN
值。你知道吗如果有什么不清楚或您有任何问题,请告诉我!:)
相关问题 更多 >
编程相关推荐