如何在 pandas 中有条件地转置(类似于使用 group by 时的 SQL 情况)

How to conditionally transpose in pandas (similar to SQL case when withn group by)

我有一个如下所示的数据框

ID name       Value
1  Brand       B1
1  Color       C1 
1  Dimension   D1
2  Brand       B2
2  Color       C2 
2  Dimension   D2

我想转置它以便结果数据框是(注意我不想为每个名字创建一列)

ID Brand Color
1  B1    C1
2  B2    C2

在 pandas 中探索了 "Unstack",但这将转置 name 的所有值。有没有一种方法可以只对名称的选定值进行转置。下面的

的 pandas 等价物是什么
Select Id , 
(case when name = "Brand" then value else end ) as brand ,
(case when name = "COlor" then value else end) as color
from table 
group by ID 

我会使用 pivot 作为:

a = df.pivot(index='ID', columns='name', values='Value')

这个returns:

name Brand Color Dimension
ID                        
1       B1   C1         D1
2       B2   C2         D2

然后您可以只选择您需要的列:

a[['Brand','Color']]

那个 returns:

name Brand Color
ID              
1       B1   C1 
2       B2   C2 

编辑:IIUC,您可以首先屏蔽您的数据框,仅保留您感兴趣的 name 列中的值:

df = df[df['name'].isin(['Brand','Color'])]

然后如上旋转。

Fabio 的解决方案很好,但您不必复制 DataFrame:

name_filter = ['Brand','Color']

print(df[df.name.isin(name_filter)].pivot(index='ID', columns='name', values='Value'))

更新:

df2 = df[df.name.isin(name_filter)].pivot(index='ID', columns='name', values='Value').reset_index()
print(df2.to_string(index=False))

输出:

 ID Brand Color
  1    B1    C1
  2    B2    C2

这是你想要的吗?