Zanam
Zanam

Reputation: 4807

Applying percentile values stored in dataframe to an array

I have a percentile dataframe df as follows:

            col1   col2     
GDStart                                                                   
2019-09-02  100    11  
2019-09-03   60    16  
2019-09-04   60    67  

I have another array data:

array([1.65 , 1.68 , 1.755, 1.76 , 1.63 ])

I need to perform the following using information in df to get percentile dataframe dt:

import numpy as np

            col1                       col2     
GDStart                                                                   
2019-09-02  np.percentile(data, 100)   np.percentile(data, 11)
2019-09-03  np.percentile(data, 60)    np.percentile(data, 16)  
2019-09-04  np.percentile(data, 60)    np.percentile(data, 67)  

I am not sure how to map the dataframe with np.percentile.

Upvotes: 0

Views: 176

Answers (2)

Terry
Terry

Reputation: 2811

IIUC you can do using apply

df = df.apply(lambda x: np.percentile(data, x))

output:

            col1    col2
GDStart     
2019-09-02  1.76    1.6388
2019-09-03  1.71    1.6428
2019-09-04  1.71    1.7310

Upvotes: 1

Andy L.
Andy L.

Reputation: 25259

Use listcomp and np.transpose

df[:] = np.transpose([np.percentile(data, df[col]) for col in df])

Out[546]:
            col1    col2
GDStart
2019-09-02  1.76  1.6388
2019-09-03  1.71  1.6428
2019-09-04  1.71  1.7310

Upvotes: 1

Related Questions