基于列名和行名的移位值

问题描述 投票:-3回答:1

我想根据Letter的Type列移动值。目前,我拥有此数据集,并使用功能melt来清理数据。

enter image description here

这是我想要的最终结果:

enter image description here

这是我尝试过的代码:

df = pd.melt(df,id_vars['Name','Type'])
<Idk what is the next step>
The code should be like this:
if df.column=='B', then df['Type']=='BB', value is S
if df.column=='C', then df['Type']=='CC', value is W

以获取我所谈论的内容的参考:

enter image description here

python pandas shift
1个回答
0
投票

raw_data中的当前“类型”列是绝对的,因为它没有引用其行中的数据。您需要删除此列,然后使用其余带有真实数据的列来创建真实的“类型”列。

df = raw_data.drop('Type', axis=1).dropna()
df = df.melt(id_vars=['Name'], var_name='Type', value_name='Rates').sort_values(['Name', 'Type'])
df['Type'] += df['Type'] # To get 2 identical letters for the Type
df

输出:

   Name Type Rates
1  Jack   AA     S
3  Jack   BB     S
5  Jack   CC     A
0  John   AA     W
2  John   BB     S
4  John   CC     W
© www.soinside.com 2019 - 2024. All rights reserved.