如何根据条件行值取消堆叠或取消透视 pandas 数据框?

how to unstack or unpivot a pandas dataframe based on conditional row values?

我有一个 pandas 数据框,如下所示:

但我需要拉出 table 并主持他们自己的专栏,以便像这样并排比较:

因此 amount 中的值为零,现在出现在新列中。

我不确定如何有条件地取消堆叠。我可以拆开整个 'furniture' 列,但如何只对特定的行值进行拆分?

您可以创建一个掩码,然后使用布尔索引:

m_table = df["furniture"] == "table"
m_chair = df["furniture"] == "chair"

df["table"] = np.where(m_table, df["amount"], 0)
df["chair"] = np.where(m_chair, df["amount"], 0)

df.loc[m_table | m_chair, "amount"] = 0
print(df)

打印:

   CID furniture  amount  table  chair
0    1     couch       2      0      0
1    2     couch       3      0      0
2    2     chair       0      0      1
3    3     table       0      3      0
4    1     chair       0      0      1
5    4      lamp       5      0      0
6    4     chair       0      0      1
7    5     couch       2      0      0
8    2      lamp       5      0      0

让我们试试get_dummies

df = df.join(df.furniture.where(df.furniture.isin(["table","chair"]),'amount').str.get_dummies().mul(df.pop("amount"),0))
df
Out[87]: 
   CID furniture  amount  chair  table
0    1     couch       2      0      0
1    2     couch       3      0      0
2    2     chair       0      1      0
3    3     table       0      0      3
4    1     chair       0      1      0
5    4      lamp       5      0      0
6    4     chair       0      1      0
7    5     couch       2      0      0
8    2      lamp       5      0      0