如何在pandas中的数据框中存储数据

问题描述 投票:1回答:1

我有一个时间序列数据,说机读如下(说)

df['machine_r'] = [1,2,1,5,3,4,5,1,2,3,4,5,7,8,1,2.....] 

如何更改数据框如下

If data in dataframe <= 25 percentile, value = 0.25, 
if 25p < data <=50p  value =  0.50,
if 50p<data <= 75p, value = 0.75,
if data>75p , value = 1

我试过了

p25 = df['machine_r'].quantile(0.25)  ## p25 is 25 percentile 
p50 = df['machine_r'].quantile(0.5)
p75 = df['machine_r'].quantile(0.8)
p100 = df['machine_r'].quantile(1)
bins = [-100,p25,p50,p75,p100]
labels = [0.25, 0.5,0.75,1]
df['machine_r'] = pd.cut(df['copper'], bins=bins,labels=labels)

但它返回0,0.25,0.5,0.75,1作为分类值,但我需要它们作为浮动进行进一步分析。怎么做到呢?

python pandas dataframe statistics
1个回答
1
投票

您可以通过astype将其强制转换为浮动:

df['new'] = pd.cut(df['machine_r'], bins=bins,labels=labels).astype(float)

更好的是使用像qcut提到的Sandeep Kadapa

df['new'] = pd.qcut(x=df.machine_r, q=[0, .25, .5, .8, 1.], labels=labels).astype(float)
print (df)
    machine_r   new
0           1  0.25
1           2  0.50
2           1  0.25
3           5  0.75
4           3  0.50
5           4  0.75
6           5  0.75
7           1  0.25
8           2  0.50
9           3  0.50
10          4  0.75
11          5  0.75
12          7  1.00
13          8  1.00
14          1  0.25
15          2  0.50

print (df.dtypes)
machine_r      int64
new          float64
dtype: object
© www.soinside.com 2019 - 2024. All rights reserved.