1

I am relatively new to Python so pardon my question if it's relatively basic (have not been able to find anything helpful online).

I have a dataframe that has 3 columns, Fund | Investor | Quantity, and need to insert a new column into my dataframe that calculates each investors' pro-rata ownership.

I assume looping through the dataframe is the best way to do this but am having issues.

enter image description here

Zoe
  • 27,060
  • 21
  • 118
  • 148
jrass
  • 37
  • 4

3 Answers3

0

It would be very easy if you can post your code but for reference you can use like:

df['D'] = df['A'] + df['B'] + df['C']

try above way in your existing code. Let me know if it helps.

0

try:

df['percent'] = df['QTY'] / df.groupby('Fund')['QTY'].transform('sum') * 100
Terry
  • 2,761
  • 2
  • 14
  • 28
0

See this question. Therefore you can group and apply:

In [1]: df = pd.DataFrame([
   ...:     ['Fund 1','Investor A', 10],
   ...:     ['Fund 1','Investor B', 20],
   ...:     ['Fund 2','Investor A', 30],
   ...:     ['Fund 2','Investor B', 40],
   ...:     ['Fund 2','Investor C', 30],
   ...:     ['Fund 3','Investor A', 50],
   ...:     ['Fund 3','Investor B', 50],
   ...: ], columns=['Fund','Investor', 'Qty'])
   ...:

In [2]: df['wanted'] = df.groupby('Fund').Qty.apply(lambda x: x/x.sum())

In [3]: df
Out[3]:
     Fund    Investor  Qty    wanted
0  Fund 1  Investor A   10  0.333333
1  Fund 1  Investor B   20  0.666667
2  Fund 2  Investor A   30  0.300000
3  Fund 2  Investor B   40  0.400000
4  Fund 2  Investor C   30  0.300000
5  Fund 3  Investor A   50  0.500000
6  Fund 3  Investor B   50  0.500000

The last step towards the percentages will be easy for you.

Nico Albers
  • 1,556
  • 1
  • 15
  • 32
  • Thank you for your answer and apologies for duplicating. This works as expected. I do get a message," 89: SettingWithCopyWarning", that i may need to look into – jrass Mar 08 '19 at 23:31
  • You're welcome! For the warning see for example [this](https://stackoverflow.com/questions/20625582/how-to-deal-with-settingwithcopywarning-in-pandas). In case this doesn't help you feel free to open a new question :-) – Nico Albers Mar 09 '19 at 08:49