I have a pandas DataFrame:
Name Col_1 Col_2 Col_3
0 A 3 5 5
1 B 1 6 7
2 C 3 7 4
3 D 5 8 3
I need to create a Series object with the values of (Col_1-Col_2)/Col_3 using groupby, so basically this:
Name
A (3-5)/5
B (1-6)/7
C (3-7)/4
D (5-8)/3
Repeated names are a possiblty, hance the groupby usage. I Created a groupby object:
df.groupby['Name']
but it seems like no groupby method fits the bill for what I'm trying to do. How can I tackle this matter?
CodePudding user response:
Use pd.Series()
method
res_df = (df['Col_1'] - df['Col_2']) / df['Col_3']
res_df = pd.Series(res_df, name='Result')
print(res_df)
0 -0.400000
1 -0.714286
2 -1.000000
3 -1.000000
Name: Result, dtype: float64
CodePudding user response:
Let's try:
df.set_index('Name').eval('(Col_1-Col_2)/Col_3')
Output:
Name
A -0.400000
B -0.714286
C -1.000000
D -1.000000
dtype: float64