我有一个 sas proc 转置,我正在尝试在 pandas 中复制。
这是一个例子:
ID = ['ID1', 'ID1', 'ID1', 'ID1', 'ID1']
obs_week = [201701,201701,201701,201701,201701]
weeks_id = [1,2,3,4,5]
spend = [100,200,300,400,500]
df = pd.DataFrame(zip(ID, obs_week, weeks_id, spend ), columns = ['id', 'obs_week', 'weeks_id', 'spend'])
df
这给出了这样的表格:
id obs_week weeks_id spend
0 ID1 201701 1 100
1 ID1 201701 2 200
2 ID1 201701 3 300
3 ID1 201701 4 400
4 ID1 201701 5 500
我正在尝试转置它,以便 ID1 和 obs_week 变得唯一,然后weeks_id 成为带有前缀的新列。
sas代码如下所示:
proc transpose data=spend out=spend_hh (drop = _label_ _name_) prefix=spend_;
by id obs_week;
id weeks_id;
var spend;
run;
我已经设法使用 df.pivot_table 接近
df.pivot_table(index=['id','obs_week'], columns='weeks_id', aggfunc=sum, fill_value=0)
提供这样的桌子
spend
weeks_id 1 2 3 4 5
id obs_week
ID1 201701 100 200 300 400 500
我的问题是我想将 1 2 3 4 5 重命名为spend_1、spend_2等
我也想对文件中的多个不同变量执行此操作,但我假设我可以将选择限制为我想要的字段
我的答案应该是这样的:
id obs_week spend_1 spend_2 spend_3 spend_4 spend_5
0 ID1 201701 100 200 300 400 500
这只是以某种方式折叠标题吗?
我还希望 id 和 obs_week 不成为索引的一部分。
reset_index
用于具有索引的列,rename_axis
用于删除 weeks_id
文本:
df = df.pivot_table(index=['id','obs_week'], columns='weeks_id', aggfunc=sum, fill_value=0)
df.columns = ['{}_{}'.format(x[0], x[1]) for x in df.columns]
df = df.reset_index().rename_axis(None, axis=1)
print (df)
id obs_week spend_1 spend_2 spend_3 spend_4 spend_5
0 ID1 201701 100 200 300 400 500
或者:
df.columns = ['_'.join((x[0], str(x[1]))) for x in df.columns]
df = df.reset_index().rename_axis(None, axis=1)
print (df)
id obs_week spend_1 spend_2 spend_3 spend_4 spend_5
0 ID1 201701 100 200 300 400 500
这是单线
In [1446]: (df.pivot_table(index=['id', 'obs_week'], columns=['weeks_id'], values='spend')
.add_prefix('spend_')
.reset_index())
Out[1446]:
weeks_id id obs_week spend_1 spend_2 spend_3 spend_4 spend_5
0 ID1 201701 100 200 300 400 500
或者,
In [1449]: (df.pivot_table(index=['id', 'obs_week'], columns=['weeks_id'], values='spend')
.add_prefix('spend_')
.reset_index()
.rename_axis(None, axis=1))
Out[1449]:
id obs_week spend_1 spend_2 spend_3 spend_4 spend_5
0 ID1 201701 100 200 300 400 500