Reputation: 79
I want to apply my function to dataframe but it shouldn't effect first row. Becouse it is my sum row. When I apply function to dataframe it divide the first row also. I am trying to each value divide by first row value.
How can I succes it? And also I want to show results with two decimals, like 40,00 not *40,0.
Here my function and data frame
df1 = pd.DataFrame(np.array([[200,200],[40,40],[80,80],[80,80]]), columns=
["Erkek","Kadin"], index=["Base","AB","C1","C2"])
def yuzde(x):
x = x/x[0]
x = x*100
return round(x,2)
tablo = df1.apply(yuzde, axis=0)
print(tablo)
my output is :
Erkek Kadin
Base 100.0 100.0
AB 20.0 20.0
C1 40.0 40.0
C2 40.0 40.0
but I want it like;
Erkek Kadin
Base 200 200
AB 20.00 20.00
C1 40.00 40.00
C2 40.00 40.00
Thank you,
Upvotes: 2
Views: 118
Reputation: 862406
I suggest dont use apply
, because slow, better is use vectorized soluton with div
and iloc
:
df1.iloc[1:] = df1.iloc[1:].div(df1.iloc[0]).mul(100)
print (df1)
Erkek Kadin
Base 200.0 200.0
AB 20.0 20.0
C1 40.0 40.0
C2 40.0 40.0
If need change format is it possible, but get string
s add applymap
:
df1.iloc[1:] = df1.iloc[1:].div(df1.iloc[0]).mul(100).applymap('{:,.2f}'.format)
print (df1)
Erkek Kadin
Base 200 200
AB 20.00 20.00
C1 40.00 40.00
C2 40.00 40.00
print (df1.applymap(type))
Erkek Kadin
Base <class 'int'> <class 'int'>
AB <class 'str'> <class 'str'>
C1 <class 'str'> <class 'str'>
C2 <class 'str'> <class 'str'>
df1.iloc[1:] = df1.iloc[1:].div(df1.iloc[0]).mul(100).applymap('{:,.2f}'.format)
df1 = df1.astype(str)
print (df1)
Erkek Kadin
Base 200 200
AB 20.00 20.00
C1 40.00 40.00
C2 40.00 40.00
print (df1.applymap(type))
Erkek Kadin
Base <class 'str'> <class 'str'>
AB <class 'str'> <class 'str'>
C1 <class 'str'> <class 'str'>
C2 <class 'str'> <class 'str'>
Upvotes: 1