pandas int或float列到百分比分布 [英] pandas int or float column to percentage distribution
本文介绍了pandas int或float列到百分比分布的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个熊猫数据框df:
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
我想基于列表(值)中的值来转换此数据域(DF).
I want to transform this datafarme (DF) based on values in the list (values).
values = [0,200,400,600]
在df中,第一个数字250.它在列表values
中介于200和400之间,因此(| 200-250 |)/(400-200)= 0.25和(400-250)/(400-200) )分别为0.75.如果缺少数据(np.nan),则必须用0填充行.我要以这种方式将其转换为代表此数据帧的数据.
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.
所需数据框:
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
推荐答案
这是使用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
这篇关于pandas int或float列到百分比分布的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文