python - Using len function in pandas -


for particular data frame, need number of females hence used following code.

 f = df.loc[df['sex']== 'female' ,'sex']  print(len(f))     >>>314 

but need length of several other items hence tried make function calculate length , put extracted values in it. code follows:

def count_num(i):    k = len(i)    return k mf = m.apply(count_num) print(mf) >>> getting output as: 1      6 2      6 3      6 8      6 9      6 10     6 11     6 name: sex, length: 314, dtype: int64 , on...till end 

what changes should made in function?

i think need value_counts:

df['sex'].value_counts() 

it seems need:

cols = ['col1','col2','sex'] df1 = df[cols].stack().value_counts() 

sample:

df = pd.dataframe({'col1':list('accddd'),                    'sex':['female'] * 2 + ['male'] * 4,                    'c':[7,8,9,4,2,3],                    'd':[1,3,5,7,1,0],                    'e':[5,3,6,9,2,4],                    'col2':list('gggtrr')})  print (df)    c  d  e     sex col1 col2 0  7  1  5  female       g 1  8  3  3  female    c    g 2  9  5  6    male    c    g 3  4  7  9    male    d    t 4  2  1  2    male    d    r 5  3  0  4    male    d    r  cols = ['col1','col2','sex'] df1 = df[cols].stack().value_counts() print (df1) male      4 g         3 d         3 c         2 r         2 female    2         1 t         1 dtype: int64 

Comments

Popular posts from this blog

node.js - Node js - Trying to send POST request, but it is not loading javascript content -

javascript - Replicate keyboard event with html button -

javascript - Web audio api 5.1 surround example not working in firefox -