Python添加一个新列,并以另一列为条件填充值

时间:2020-05-14 15:55:26

标签: python performance dataframe

Python noob在这里。在下面的数据框中,我想添加一个新列,该列的值取决于col2中的值。

df = pd.DataFrame({'col1': [1, 2, 10, 9], 'col2': [3, 4, 5, 6]})

   col1  col2
0     1     3
1     2     4
2    10     5
3     9     6

添加一个新列'col3',使-如果in:col2中的值<5,则填充'In',> 5填充'Out',= 5填充5。所需的输出如下。

   col1  col2 col3
0     1     3   In
1     2     4   In
2    10     5    5
3     9     6  Out

我已经可以使用for循环来执行此操作,但是在大型数据集上似乎效率不高。有什么简单的方法吗?

2 个答案:

答案 0 :(得分:2)

我找到3种方法来做到这一点:使用np.wherepd.locpd.apply(以及@ OO7 here的建议)

def using_where(df):
    df['col3'] = np.where(df['col2']>5, 'Out', np.where(df['col2']<5, 'In', 5))
    return df

def using_apply(df):
    df['col3'] = df['col2'].apply(lambda x: 5 if x == 5 else ('In' if x < 5 else 'Out'))
    return df

def using_loc(df):
    df['col3'] = 5
    df.loc[df['col2']>5, 'col3'] = 'Out'
    df.loc[df['col2']<5, 'col3'] = 'In'
    return df

我对它们全部进行了剖析,并且根据size中的dataframe,它们的表现似乎有所不同:

size = 10**4
df = pd.DataFrame({'col1': np.random.randint(0, 10, size), 'col2': np.random.randint(0, 10, size)})
%timeit using_where(df)
%timeit using_apply(df)
%timeit using_loc(df)

使用size = 10**4输出:

1000 loops, best of 3: 1.97 ms per loop
100 loops, best of 3: 2.11 ms per loop
100 loops, best of 3: 4.14 ms per loop

使用size = 10**5输出:

100 loops, best of 3: 18.6 ms per loop
100 loops, best of 3: 17.5 ms per loop
100 loops, best of 3: 11.9 ms per loop

最后,我要说的是,您应该尝试使用实际的dataframe对自己进行配置,并为您的应用选择最快的方法。 希望这会有所帮助!

答案 1 :(得分:1)

尝试

df = pd.DataFrame({'col1': [1, 2,10,9], 'col2': [3, 4,5,6]})
df['col3'] = df['col2'].apply(lambda x: '5' if x == 5 else ('In' if x < 5 else "Out"))
df

enter image description here

相关问题