我有以下df
code y_m date_1 date_2
10 201710 2017-10-01 2017-10-06
10 201710 2017-10-07 2017-10-09
10 201711 2017-11-06 2017-11-08
10 201711 2017-11-02 2017-11-06
20 201710 2017-10-03 2017-10-04
20 201710 2017-10-07 2017-10-08
20 201711 2017-11-06 2017-11-09
20 201711 2017-11-02 2017-11-03
code
和y_m
是 str
, date_1/2
是 ISODate
.
我想先groupby code
和y_m
,并计算date_2-date_1
创建一个新列 avg_days
对于 Timedelta
每组中的值,
code_yr_mon_grp_by = df.groupby(['code', 'y_m'])
code_yr_mon_gr_avg_days = code_yr_mon_grp_by.apply(lambda row: (row['date_2'] - row['date_1']) / np.timedelta64(1, 'D')).mean(level=[0, 1]).reset_index(name='avg_days')
这将生成
code y_m avg_days
10 201710 3.5
10 201711 3
20 201710 1
20 201711 2
然后我想将这个 df 转换为转置列 y_m
的矩阵要划船,请输入 avg_days
作为矩阵单元格值,
0 1 2 3
0 -1 0 201710 201711
1 0 2.375 2.25 2.5
2 10 3.25 3.5 3
3 20 1.5 1 2
具体来说,-1
表示一个虚拟值,指示特定 code
的 y_m 不存在值或维持矩阵形状; 0
代表“所有”值,即 code
的平均值或y_m
或code
和y_m
,例如单元格 (1, 1) 平均 avg_days
所有人的值(value)y_m
和code
; (1,2)
平均 avg_days
对于 201710
跨越code
10
和20
.
但是当我尝试
def convert_to_matrix(df, p_tab_idx, p_tab_cols, p_tab_vals, p_tab_agg_func):
df_tab = (df.pivot_table(index=p_tab_idx,
columns=p_tab_cols,
values=p_tab_vals,
margins=True,
aggfunc=p_tab_agg_func,
fill_value=-1,
margins_name='0'))
# change order of index and columns values for reindex
idx = df_tab.index[-1:].tolist() + df_tab.index[:-1].tolist()
cols = df_tab.columns[-1:].tolist() + df_tab.columns[:-1].tolist()
df_tab = (df_tab.reindex(index=idx, columns=cols)
.reset_index()
.rename(columns={p_tab_idx: -1})
.rename_axis(None, 1))
# add columns to first row
df_tab = df_tab.columns.to_frame().T.append(df_tab).reset_index(drop=True)
# reset columns names to range
df_tab.columns = range(len(df_tab.columns))
# converts column labels from int to str
df_tab.columns = df_tab.columns.astype(str)
return df_tab
code_yr_mon_gr_proc_days_p_tab = convert_to_matrix(code_yr_mon_gr_avg_days,
p_tab_idx='code',
p_tab_cols='y_m',
p_tab_vals='avg_days',
p_tab_agg_func='mean')
我收到错误
builtins.AttributeError: 'Index' object has no attribute 'to_frame'
我想知道如何解决这个问题并达到预期的结果。
最佳答案
如果 pandas 版本低于 0.21.0
其中 Index.to_frame
未实现使用:
df_tab = (pd.DataFrame(df_tab.columns, index=df_tab.columns)
.T
.append(df_tab)
.reset_index(drop=True))
相反:
df_tab = df_tab.columns.to_frame().T.append(df_tab).reset_index(drop=True)
关于python - pandas hub_table 获取列和行中的平均值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49966396/