基于列条件的移位单元格值

问题描述 投票:0回答:2

我想根据列和A B C以及“类型”列内部的值进行移位。

这是我的数据框:

Name   Type   A   B   C
John   AR     W   S   W
John   BR   
John   CR
Jack   AR     S   S   A
Jack   BR   
Jack   CR

使用融合功能之前所需的数据框:

Name   Type   A   B   C
John   AR     W       
John   BR         S
John   CR             W
Jack   AR     S       
Jack   BR         S
Jack   CR             A
pandas shift
2个回答
0
投票

尝试在每列上使用移位功能:

import pandas as pd

df = pd.DataFrame({'A':['W','','','S','',''],'B':['S','','','S','',''],'C':['W','','','A','','']})

df.B = df.B.shift(1)

df.C = df.C.shift(2)

0
投票

您可以使用它。

def func(x):
    for col in x.columns[2:]:
        for index,val in x.iterrows():
            if val.Type[0]==col:
                x[col]=x[col].shift(index-x.index[0])
    return x
df.groupby('Name').apply(func)

输入

    Name    Type    A       B       C
0   John    AR      W       S       W
1   John    BR     None     None    None
2   John    CR     None     None    None
3   Jack    AR     S        S       A
4   Jack    BR     None     None    None
5   Jack    CR     None     None    None

输出

    Name    Type    A       B       C
0   John    AR      W       NaN     NaN
1   John    BR      None    S       NaN
2   John    CR      None    None    W
3   Jack    AR      S       NaN     NaN
4   Jack    BR      None    S       NaN
5   Jack    CR      None    None    A
© www.soinside.com 2019 - 2024. All rights reserved.