2017-07-11 5 views
2

私は以下のSampleDfのようなデータを持っています。最初の '平均'、 '合計'または 'カウント'を選択するコードを作成しようとしています新しい列 'Agg'に入れてください。私は以下のコードはほとんどそれを行うが、それは階層を持っています。それで、コードでは、CountがSumの前に来る場合、Sumを 'Agg'カラムに入れます。私は以下のOutputDfを持って、私が得たいものを示しています。場合は、最初に発生する、すなわち目的の任意の期間、[「平均」、「和」、「カウント」] -
を:発生順序に基づいて文字列を解析する

Sample Data: 

SampleDf=pd.DataFrame([['tom',"Avg(case when Value1 in ('Value2') and [DateType] in ('Value3') then LOS end)"],['bob',"isnull(Sum(case when XferToValue2 in (1) and DateType in ('Value3') and [Value1] in ('HM') then Count(LOS) end),0)"]],columns=['ReportField','OtherField']) 

Sample Output: 

OutputDf=pd.DataFrame([['tom',"Avg(case when Value1 in ('Value2') and [DateType] in ('Value3') then LOS end)",'Avg'],['bob',"isnull(Sum(case when XferToValue2 in (1) and DateType in ('Value3') and [Value1] in ('HM') then Count(LOS) end),0)",'Sum']],columns=['ReportField','OtherField','Agg']) 


Code: 
import numpy as np 

    SampleDf['Agg'] = np.where(SampleDf.SQLTranslation.str.contains("Sum"),"Sum", 
           np.where(SampleDf.SQLTranslation.str.contains("Count"),"Count", 
             np.where(SampleDf.SQLTranslation.str.contains("Avg"),"Avg","Nothing"))) 

答えて

1

この問題に迅速かつ汚い試みが返す関数を書くことになりますそれは、文字列
に存在するのです - そのような存在しない場合、またはNone

import re 
terms = ['Avg','Sum','Count'] 
def extractTerms(s, t=terms): 
    s_clean = re.sub("[^\w]|[\d]"," ", s).split() 
    s_array = [w for w in s_clean if w in t] 
    try: 
     return s_array[0] 
    except: 
     return None 

証明があれば、文字列内の用語:

SampleDf['Agg'] = SampleDf['OtherField'].apply(lambda s: extractTerms(s)) 
SampleDf 

ReportField OtherField Agg 
0 tom Avg(case when Value1 in ('Value2') and [DateType] in ('Value3') then LOS end) Avg 
1 bob isnull(Sum(case when XferToValue2 in (1) and DateType in ('Value3') and [Value1] in ('HM') then Count(LOS) end),0) Sum 

用語が文字列に含まれていない場合の証明:

SampleDf['Agg'] = SampleDf['OtherField'].apply(lambda s: extractTerms(s)) 
SampleDf 

ReportField OtherField Agg 
0 tom foo None 
1 bob isnull(Sum(case when XferToValue2 in (1) and DateType in ('Value3') and [Value1] in ('HM') then Count(LOS) end),0) Sum 
+0

ありがとう、それはトリックでした。 – ndderwerdo

+0

@ndderwerdoなぜ、アップアップしないの? –

+0

申し訳ありませんが、緑のチェックマークをクリックしました。私はstackoverflowのすべての習慣ではないよ。チェックでは、答えが正しく働いたことを確認していますか?アップヴォートはどういう意味ですか?私は先に進み、それにアップヴォートを与えた。間違いなくそのチップを感謝します! – ndderwerdo

関連する問題