I have a dataframe which contains a column labeled Pool. I want to create a new column labeled “Volume” which is 310 divided by the occurrence of each value of Pool. For example there are three occurrences of Pool 1 so 310/3 = 103.3. There are 4 occurrences of Pool 2 so 310/4 = 77.5 and so forth. Any ideas on how to do this with Pandas?
Pool | Volume |
---|---|
1 | 103.3 |
1 | 103.3 |
1 | 103.3 |
2 | 77.5 |
2 | 77.5 |
2 | 77.5 |
2 | 77.5 |
3 | 62 |
3 | 62 |
3 | 62 |
3 | 62 |
3 | 62 |
I tried:
df["Volume"] = 310 / pool.get_group(1).value_counts()
Thanks for your help.
New contributor
Michael Davila is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
Use:
df["Volume"] = 310 / df['Pool'].map(df['Pool'].value_counts())
Or:
df["Volume"] = 310 / df.groupby('Pool')['Pool'].transform('size')
print (df)
Pool Volume
0 1 103.333333
1 1 103.333333
2 1 103.333333
3 2 77.500000
4 2 77.500000
5 2 77.500000
6 2 77.500000
7 3 62.000000
8 3 62.000000
9 3 62.000000
10 3 62.000000
11 3 62.000000