search

Home  >  Q&A  >  body text

Find the proportion of each value in the column using pandas in python

For example, I have a dataframe called df

   Prices  Amount Action  C
0       3      57   Sell  1
1      89      42   Sell  1
2      45      70    Buy -1
3       6      43   Sell  1
4      60      47   Sell  1
5      19      16    Buy -1
6      56      89   Sell  1
7       3      28    Buy -1
8      56      69   Sell  1
9      90      49    Buy -1

The method currently used is

df['Prices'].apply(lambda x :x/df['Prices'].sum())

It feels very slow. Is there any faster way?

滿天的星座滿天的星座2748 days ago1839

reply all(2)I'll reply

  • 怪我咯

    怪我咯2017-05-18 10:57:04

    willsum()写在lambda表达式外面,否则每次计算一个x占该列的比例时,又需要重新计算sum(), wasting a lot of time.

    reply
    0
  • 某草草

    某草草2017-05-18 10:57:04

    df['Prices'] = df['Prices'] / df['Prices'].sum()

    reply
    0
  • Cancelreply