2016-09-03 7 views
0

データフレームがあります。 他の列の条件を使用して列を追加する方法

if 'month'=1,2,3 the elements = 'term1' 
    'month'=4,5  the elements = 'term2' 
    'month'=6,7  the elements = 'term3' 

は私がこのような結果を得ることができますどのように

 month term 
0  1 term1 
1  2 term1 
2  3 term1 
3  4 term2 
4  5 term2 
5  6 term3 
6  7 term3 

以下の結果を取得したいと思い

df=pd.DataFrame({'month':np.arange(1,8)}) 

だから、私は「月」列

を使用して列を追加したいと思いますか? 多分私達は簡単でシンプルな方法....

答えて

1

私はを通じて宣言的な方法のために行くだろう簡単に読むことができ、簡単に適用することができます。置換条件が大きくなるか、他の入力に依存する場合は、置換条件辞書をプログラムで生成できます。

conditions = {1:'term1', 2:'term1', 3:'term1', 
       4:'term2', 5:'term2', 
       6:'term3', 7:'term3'} 

df['term'] = df.replace(conditions) 
df 

     month term 
0  1 term1 
1  2 term1 
2  3 term1 
3  4 term2 
4  5 term2 
5  6 term3 
6  7 term3 
+0

非常に簡単です!この列をdfに追加するにはどうすればよいですか? – Heisenberg

+1

通常通り: 'df ['term'] = df.replace(条件)' – Boud

+0

ありがとう!だから、月> 7 = term4とすると、どうすれば記述できますか? – Heisenberg

1

使用numpy.whereSeries.isin()方法がそれを行うためのオプションのいずれかの可能性があり、この結果を得ることができます:

import numpy as np 
import pandas as pd 
df["term"] = np.where(df.month.isin([1,2,3]), "term1", \ 
         np.where(df.month.isin([4,5]), "term2", "term3")) 

df 
# month term 
#0 1 term1 
#1 2 term1 
#2 3 term1 
#3 4 term2 
#4 5 term2 
#5 6 term3 
#6 7 term3 
関連する問題