Python Pandas Proc 转置等价物

标签 python pandas pivot-table transpose

我有一个 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

关于Python Pandas Proc 转置等价物,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45596576/

相关文章:

python - 如何在格式化用户定义标题 XLSXWriter 和 Pandas 时删除索引列

python - Pandas 映射到 TRUE/FALSE 作为字符串,而不是 bool 值

MySQL - 行到列

python - 如何将python文件中导入的库导入到另一个python文件中?

python-docx 如何将不同的样式应用于表格中的不同单元格

python - 如何从一个表中删除所有出现的数字,并从另一个表中查找数字?

python - 将列添加到数据透视表( Pandas )

excel - 获取选定的数据透视表名称 - Excel VBA

python - 为什么我不能规范化这个随机的 unicode 字符串?

python - Tweepy For Loop For IDs 提取,有些不对劲