sample_df = pd.DataFrame(np.random.randint(1,20,size=(10, 2)), columns=list('BC'))
sample_df["date"]= ["2020-02-01","2020-02-01","2020-02-01","2020-02-01","2020-02-01",
"2020-02-02","2020-02-02","2020-02-02","2020-02-02","2020-02-02"]
sample_df["date"] = pd.to_datetime(sample_df["date"])
sample_df.set_index(sample_df["date"],inplace=True)
sample_df["A"]=[10,10,10,10,10,12,1,3,4,2]
del sample_df["date"]
sample_df
def func(df,n_bins):
try:
proc_col = pd.qcut(df["A"].values, n_bins, labels=range(0,n_bins))
return proc_col
except:
proc_col = pd.qcut(df.mean(axis =1).values, n_bins, labels=range(0,n_bins))
return proc_col
sample_df["A"]=sample_df.groupby([sample_df.index.get_level_values(0)])[["C","A"]].apply(lambda df: func(df,3))
sample_df
B C A
date
2020-02-01 1 16 [1, 2, 1, 0, 0] Categories (3, int64): [0 < 1 ...
2020-02-01 5 19 [1, 2, 1, 0, 0] Categories (3, int64): [0 < 1 ...
2020-02-01 2 16 [1, 2, 1, 0, 0] Categories (3, int64): [0 < 1 ...
2020-02-01 12 11 [1, 2, 1, 0, 0] Categories (3, int64): [0 < 1 ...
2020-02-01 15 10 [1, 2, 1, 0, 0] Categories (3, int64): [0 < 1 ...
2020-02-02 19 17 [2, 0, 1, 2, 0] Categories (3, int64): [0 < 1 ...
2020-02-02 17 7 [2, 0, 1, 2, 0] Categories (3, int64): [0 < 1 ...
2020-02-02 14 1 [2, 0, 1, 2, 0] Categories (3, int64): [0 < 1 ...
2020-02-02 19 13 [2, 0, 1, 2, 0] Categories (3, int64): [0 < 1 ...
2020-02-02 15 13 [2, 0, 1, 2, 0] Categories (3, int64): [0 < 1 .