Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pandas int or float column to percentage distribution

I have a pandas dataframe df:

import pandas as pd
import numpy as np
data = {'A':[250,100,400,np.nan,300]}
df = pd.DataFrame(data)
print(df)

       A
0  250.0
1  100.0
2  400.0
3    NaN
4  300.0

I want to transform this datafarme (DF) based on values in the list (values).

values = [0,200,400,600]

In df, first number 250. It is between 200 and 400 in list values, such that (|200-250|)/(400-200) = 0.25 and (400-250)/(400-200)=0.75,respectively. If data is missing (np.nan) then row must be filled with 0. I want to convert this respresent this dataframe in this manner.

Desired dataframe:

     0   200   400  600
0  0.0  0.25  0.75  0.0
1  0.5  0.50  0.00  0.0
2  0.0  0.00  1.00  0.0
3  0.0  0.00  0.00  0.0
4  0.0  0.50  0.50  0.0
like image 668
SS23 Avatar asked Jul 23 '19 18:07

SS23


1 Answers

Here is one way using pd.cut

s=pd.cut(df.A,values).dropna()
x=s.map(lambda x : x.left).astype(int).to_frame('V')
y=s.map(lambda x : x.right).astype(int).to_frame('V')
x['r']=(df.A-x.V)/(y.V-x.V)
y['r']=(y.V-df.A)/(y.V-x.V)
df1=pd.concat([x,y]).set_index('V',append=True).\
       r.unstack(fill_value=0).\
        reindex(columns=values,index=df.index,fill_value=0)
df1
Out[110]: 
V  0     200   400  600
0  0.0  0.25  0.75  0.0
1  0.5  0.50  0.00  0.0
2  0.0  1.00  0.00  0.0
3  0.0  0.00  0.00  0.0
4  0.0  0.50  0.50  0.0
like image 152
BENY Avatar answered Sep 26 '22 23:09

BENY