Reputation: 1059
I have a dataFrame of the form:
0
college gender
Engineering F 117
M 2240
and I want to change it to:
college M:F
Engineering 19:1
where M:F represents the ratio of Male to Female.
Is there anyway to do this with pandas without iterating over all rows?
Upvotes: 1
Views: 130
Reputation: 862831
It seems you need reshape by unstack
and then divide:
df = df.unstack()[0]
#same as
#df = df[0].unstack()
df['M:F'] = df['M'] / df['F']
#same as
#df['M:F'] = df['M'].div(df['F'])
print (df)
0
college gender
Engineering F 117
M 2240
Engineering1 F 117
M 2240
df = df.unstack()[0]
df['M:F'] = df['M'].div(df['F'])
print (df)
gender F M M:F
college
Engineering 117 2240 19.145299
Engineering1 117 2240 19.145299
print (df[['M:F']])
gender M:F
college
Engineering 19.145299
Engineering1 19.145299
Upvotes: 1