2017-07-01 60 views
-1

下面是我的python數據框表。我想要的結果是在突出顯示的黃色列中。根據字符串值在另一個字段中使用文本創建數據框中的新字段

enter image description here

下面是代碼的邏輯我想要實現:

  • 如果「獎」列包含單詞「前愛爾蘭共和軍顧問」,那麼我希望「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

回答

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) 
+0

thx for response。不幸的是,它沒有工作......每一行都回來'真' – PineNuts0

+0

@ PineNuts0奇怪,因爲我使用了一個獨立的例子,並且早些時候使用.match()。我重新看了你的例子,改變正則表達式代碼也適用於我... df_rfholder ['Industry_Recognition_Flag'] = np.where(df_rfholder ['Award']。str.contains('。* Top IRA Advisor',regex = True ),'公認爲頂級IRA顧問','') –

+0

thx爲迴應;我的問題是,即使價值沒有在「獎勵」字段中表示頂級IRA顧問,Industry_Recognition_Flag字段仍然會顯示「被公認爲頂級IRA顧問」 – PineNuts0

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 
相關問題