Given a df
0.54881,0.71519
0.60276,0.54488
0.42365,0.64589
0.43759,0.89177
0.96366,0.38344
I would like to reindex the df as below
(0,10) 0.54881,0.71519
(10,20) 0.60276,0.54488
(20,30) 0.42365,0.64589
(30,40) 0.43759,0.89177
(40,50) 0.96366,0.38344
I have the impression this can be done via pd.IntervalIndex.from_breaks
However, the following code
import numpy.random
import pandas as pd
import numpy as np
numpy.random.seed(0)
df=pd.DataFrame(np.random.rand(5,2),columns=['a','b'])
index = pd.IntervalIndex.from_breaks(range(0,60,10))
result = pd.DataFrame(index=index, data=df)
Output
a b
(0, 10] NaN NaN
(10, 20] NaN NaN
(20, 30] NaN NaN
(30, 40] NaN NaN
(40, 50] NaN NaN
May I know what is the issue?
CodePudding user response:
You need to assign the value when create the df
numpy.random.seed(0)
df=pd.DataFrame(np.random.rand(5,2),columns=['a','b'])
index = pd.IntervalIndex.from_breaks(range(0,60,10))
result = pd.DataFrame(index=index, data=df.to_numpy())