Python 如何根据条件将列值更改为行值
df: df_输出:Python 如何根据条件将列值更改为行值,python,pandas,Python,Pandas,df: df_输出: items M1 v1 v2 v3 A c1 56 52 25 A c2 66 63 85 B c1 29 76 36 B c2 14 24 63 我需要将列值更改为行值,如示例所示。 我尝试了一些stack()函数,但它不起作用。您希望将堆栈和取消堆栈: items M1 C1
items M1 v1 v2 v3
A c1 56 52 25
A c2 66 63 85
B c1 29 76 36
B c2 14 24 63
我需要将列值更改为行值,如示例所示。
我尝试了一些stack()函数,但它不起作用。您希望将
堆栈
和取消堆栈
:
items M1 C1 C2
A V1 56 66
A V2 52 63
A V3 25 85
B V1 29 14
B V2 76 24
B V3 36 60
输出:
(df.set_index(['items','M1'])
.unstack('M1') # unstack promotes M1 to columns
.stack(level=0) # stack turns original columns to index level
.rename_axis(columns=None, index=['item','M1']) # rename to match output
.reset_index()
)
您希望组合
堆栈
和取消堆栈
:
items M1 C1 C2
A V1 56 66
A V2 52 63
A V3 25 85
B V1 29 14
B V2 76 24
B V3 36 60
输出:
(df.set_index(['items','M1'])
.unstack('M1') # unstack promotes M1 to columns
.stack(level=0) # stack turns original columns to index level
.rename_axis(columns=None, index=['item','M1']) # rename to match output
.reset_index()
)
我收到此错误值错误:索引包含重复项,无法reshape@KRAJA您有重复的数据,例如,两行具有相同的
项=='A'
和'M1=='C1'。您想如何合并它们?我得到了这个错误值错误:索引包含重复的条目,无法合并reshape@KRAJA您有重复的数据,例如,两行具有相同的项=='A'
和'M1=='C1'。您想如何合并它们?