使用基于另一个字段中的字符串值的文本在数据框中创建新字段

时间:2017-07-01 21:07:41

标签: python string dataframe text field

下面是我的python数据框表。我想要的结果是突出显示的黄色列。

enter image description here

以下是我想要实现的代码逻辑:

  • 如果"奖励"列包含单词" Top IRA Advisor",然后我想要" Industry_Recognition_Flag"领域说"被认可为顶级IRA顾问"。否则,我希望它是空白的。

以下是我尝试过的代码,但没有成功:

df_rfholder['Industry_Recognition_Flag'] = np.where(df_rfholder['Award'].str.contains('(?:Top IRA Advisor)', regex = True), 'Recognized as Top IRA Advisor', '')

非常感谢任何帮助!

enter image description here

2 个答案:

答案 0 :(得分:0)

你可以使用.str.match()...... https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.match.html

这是一个有效的例子:

import datetime
import pandas as pd
import numpy as np

d = {'one' : pd.Series(['','2016 Top IRA Advisor','2016 Top IRA Advisor'], index=['a', 'b', 'c']), 'two' : pd.Series(['Recognized', 'Recognized', 'Recognized'], index=['a', 'b', 'c'])}

df = pd.DataFrame(d)

df["new"] = np.where(df['one'].str.match('.*Top IRA Advisor'), 'true', 'false')

print(df)

答案 1 :(得分:0)

这么简单吗?

>>> import pandas as pd
>>> data = {'Award': 8*['']+['2016 Top IRA Advisor', '', '2016 Top IRA Advisor']}
>>> df = pd.DataFrame(data)
>>> df
                   Award
0                       
1                       
2                       
3                       
4                       
5                       
6                       
7                       
8   2016 Top IRA Advisor
9                       
10  2016 Top IRA Advisor
>>> df['Desired Result']=df['Award'].apply(lambda x: 'Recognized as Top IRA Advisor' if x=='2016 Top IRA Advisor' else '')
>>> df
                   Award                 Desired Result
0                                                      
1                                                      
2                                                      
3                                                      
4                                                      
5                                                      
6                                                      
7                                                      
8   2016 Top IRA Advisor  Recognized as Top IRA Advisor
9                                                      
10  2016 Top IRA Advisor  Recognized as Top IRA Advisor