2016-08-23 11 views
7

मैं डेटाफ्रेम "df_energy" में एक नया कॉलम "energy_class" जोड़ने का प्रयास करता हूं जिसमें "consum_energy" मान> 400, "मध्यम" स्ट्रिंग "उच्च" होता है यदि "consum_energy" "मान 200 से 400 के बीच है, और" कम "यदि" consum_energy "मान 200 से कम है। मैं np.where numpy से उपयोग करने का प्रयास करता हूं, लेकिन मुझे लगता है कि numpy.where(condition[, x, y]) मेरे मामले में केवल दो शर्त का इलाज नहीं करता है।कई स्थितियों के साथ "जहां" कई स्थितियों के साथ

कृपया मेरी मदद करने के लिए कोई विचार कृपया?

अग्रिम धन्यवाद

उत्तर

9

आप का प्रयोग कर एक ternary कर सकते हैं:,

np.where(consumption_energy > 400, 'high', 
     (np.where(consumption_energy < 200, 'low', 'medium))) 
8

मैं cut() विधि यहाँ का प्रयोग करेंगे जो बहुत ही कुशल और स्मृति की बचत category dtype उत्पन्न करेगा:

In [124]: df 
Out[124]: 
    consumption_energy 
0     459 
1     416 
2     186 
3     250 
4     411 
5     210 
6     343 
7     328 
8     208 
9     223 

In [125]: pd.cut(df.consumption_energy, [0, 200, 400, np.inf], labels=['low','medium','high']) 
Out[125]: 
0  high 
1  high 
2  low 
3 medium 
4  high 
5 medium 
6 medium 
7 medium 
8 medium 
9 medium 
Name: consumption_energy, dtype: category 
Categories (3, object): [low < medium < high] 
4

इसे आजमाएं: @Maxu

से सेटअप का उपयोग करना
conditions = [ df2['consumption_energy'] >= 400, (df2['consumption_energy'] < 400) & (df2['consumption_energy']> 200), df2['consumption_energy'] <= 200 ] 
choices  = [ "high", 'medium', 'low' ] 

df2["energy_class"] = np.select(conditions, choices, default=np.nan) 


    consumption_energy energy_class 
0     459   high 
1     416   high 
2     186   low 
3     250  medium 
4     411   high 
5     210  medium 
6     343  medium 
7     328  medium 
8     208  medium 
9     223  medium 
2

मुझे कोड को साफ रखना पसंद है। यही कारण है कि मैं ऐसे कार्यों के लिए np.vectorize पसंद करता हूं।

def conditions(x): 
    if x > 400: 
     return "High" 
    elif x > 200: 
     return "Medium" 
    else: 
     return "Low" 

func = np.vectorize(conditions) 
energy_class = func(df_energy["consumption_energy"]) 

तो बस का उपयोग कर अपने dataframe में एक स्तंभ के रूप में numpy सरणी जोड़ें:

df_energy["energy_class"] = energy_class 

इस दृष्टिकोण में लाभ यह है कि अगर आप एक स्तंभ के लिए और अधिक जटिल की कमी जोड़ना चाहते हैं, यह किया जा सकता है आसानी से। उम्मीद है कि यह मदद करता है।

संबंधित मुद्दे