如何基于空值将一个行列值分配给另一行列

时间:2019-10-28 16:48:11

标签: python python-3.x pandas

我有一个数据框


    Col1    Col2    Col3     Col4    Col5
    A123    13500  2/03/19    0      NaN
    B123    2000   3/04/19    0     Distinct
    C123    500    8/09/19    1      Match
    D123    100    11/01/19   1      NaN
    E123    1350  2/03/19      2         NaN
    F123    2000   3/04/19    2     Match
    G123    500    8/09/19    3      Distinct
    H123    100    11/01/19   3      NaN

我想遍历基于Col4的行,并相应地更新Col5(NaN)行。

也就是说,当我选择Col4为0的行时,我想根据其他行列的值来更新Col5

Output:

    Col1    Col2    Col3     Col4    Col5
    A123    13500  2/03/19    0     **Distinct**
    B123    2000   3/04/19    0     Distinct
    C123    500    8/09/19    1      Match
    D123    100    11/01/19   1      **Match**
    E123    1350  2/03/19      2        **Match**
    F123    2000   3/04/19    2      Match
    G123    500    8/09/19    3      Distinct
    H123    100    11/01/19   3     **Distinct**

3 个答案:

答案 0 :(得分:0)

我认为您正在寻找的是功能np.where。我假设您要在Col5时将值'Distinct'分配给Col4 = 0,在Col4 = 1时将值'Match'分配给。然后您的代码将是:

df['Col5'] = np.where(df.Col4==0, 'Distinct', 'Match')

当然,您可以根据需要的条件语句修改代码

答案 1 :(得分:0)

从您的逻辑来看,您似乎希望将*中的0.3值映射到'*'中的“ Distinct”,并将1,2值映射到“ Match”。您只想更新Col4中的Col5值。

尝试:

NaN

您现在得到:

Col5

如果您改变了对逻辑或替换值的看法,这将使以后轻松更改映射变得容易。

答案 2 :(得分:0)

好的,我在这里假设两件事:

1)第4列中每个数字只有两个条目

2)Col4中两个具有相同编号的条目都彼此相邻放置(实际上没关系,如果不是这种情况,则始终可以按Col4对数据帧进行排序,并且会遇到这种情况)< / p>

代码如下:

df = df.replace(np.nan,"None")
txt = "None"
for i in range(df.Col4.size):
    if (df.loc[i,'Col5']=="None"):
        df.loc[i,'Col5'] = txt
        txt = "None"
    else: 
        txt = df.loc[i,'Col5']

txt = "None"
for i in reversed(range(df.Col4.size)):
    if (df.loc[i,'Col5']=="None"):
        df.loc[i,'Col5'] = txt
        txt = "None"
    else: 
        txt = df.loc[i,'Col5']

我在这里执行3个步骤。

1)将所有nan替换为字符串,以便在使用if时没有任何数据类型比较问题。

2)按升序循环。如果Col5中的值为“无”,则将其替换为“ txt”中的值。否则,“ txt”变量将其值存储在Col5中。

3)反向执行相同的循环。

我希望这可以解决您的问题。