pandas int或float列到百分比分布

SS2*_*S23 5 python numpy python-3.x pandas

我有一个熊猫数据框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
Run Code Online (Sandbox Code Playgroud)

我想根据列表(值)中的值来转换此数据仓库(DF)。

values = [0,200,400,600]
Run Code Online (Sandbox Code Playgroud)

在df中,第一个数字为250。它在list values中介于200和400之间,使得(| 200-250 |)/(400-200)= 0.25和(400-250)/(400-200)= 0.75。如果缺少数据(np.nan),则必须用0填充行。我要以这种方式将此表示为数据框的值进行转换。

所需的数据框:

     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
Run Code Online (Sandbox Code Playgroud)

WeN*_*Ben 5

这是使用的一种方法 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
Run Code Online (Sandbox Code Playgroud)