python - Adding a conditional column to a datframe if the value is in a list -


i have pandas dataframe column called 'letters' has letters of alphabet values. first row 'c', next row 'z', next 'm' on , forth:

letters

c

z

m

a

b

o

....

i have lists groups letters of alphabet fall, so:

early_alph = ['a','b','c'....'m'] late_alph = ['n','o','p'....'z'] 

i to add new column dataframe groups letters of alphabet depending on list in. if sql write following:

%let early_alph = ('a','b','c'....'m'); %let late_alph = ('n','o','p'....'z');  create table my_df   select    letters,    case when letters in &early_alph. 'early_alph'         when letters in &late_alph 'late_alph'         else 'unknown' end 'alph_group' my_table; 

the output looking is:

letters alph_group

c early_alph

z late_alph

m early_alph

a early_alph

b early_alph

o late_alph

i'm new python , pandas, in research seems numpy's np.where promising, every example found tested against 1 value (rather list of values). appreciated.

one way nested where.

np.where(df.letters.between('a', 'm'), 'early_alph', np.where(df.letters.between('n','z'), 'late_alph', 'unknown') 

Comments

Popular posts from this blog

ios - MKAnnotationView layer is not of expected type: MKLayer -

ZeroMQ on Windows, with Qt Creator -

unity3d - Unity SceneManager.LoadScene quits application -