有没有一种比“ for”更快的方法来比较列中的值以选择我想要的值?

时间:2019-07-19 18:05:20

标签: python pandas

我在数据框中有这两个不同的列。我想迭代并知道列'Entry_Point'是否为Str,然后在Delivery_Point中放入Client_Num

df
Client_Num     Entry_Point        Delivery_Point
1                      0
2                      a
3                      3
4                      4
5                      b
6                      c
8                      d

它应该像这样:

Client_Num     Entry_Point        Delivery_Point
1                     10                 10
2                      a                 2
3                      32                32
4                      14                14
5                      b                 5
6                      c                 6
8                      d                 8

我已经尝试过for,但是它花费的时间太长,尤其是当我有2万行时。

for i in range(len(df)):
   if  type(df.loc[i]['Entry_Point']) == str:
       df.loc[i]['Delivery_Point'] = df.loc[i]['Client_num']
   else:
       df.loc[i]['Delivery_Point'] = df.loc[i]['Entry_Point']

3 个答案:

答案 0 :(得分:0)

Pandas列将作为单个数据类型导入。因此,您应用的方法可能无法获取正确的结果。我认为您想执行以下操作:

df['Delivery_Point'] = df.apply(lambda x: x.Client_num if not x.Entry_Point.strip().isnumeric() else x.Entry_Point, axis=1)

答案 1 :(得分:0)

在非常大的数据集上可能会表现更好的另一种选择是使用向量化numpy函数:

import numpy as np

@np.vectorize
def get_if_str(client_num, entry_point):
    if isinstance(entry_point, str):
        return client_num
    return entry_point

df['Delivery_Point'] = get_if_str(df['Client_Num'], df['Entry_Point'])

我们可以在这里比较时间:


##slow way
def generic(df):
    for i in range(len(df)):
        if  type(df.loc[i]['Entry_Point']) == str:
            df.loc[i]['Delivery_Point'] = df.loc[i]['Client_Num']
        else:
            df.loc[i]['Delivery_Point'] = df.loc[i]['Entry_Point']

%timeit generic(df)
# 237 ms ± 5.88 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
# Miliseconds

%timeit df['Delivery_Point'] = get_if_int(df['Client_Num'], df['Entry_Point'])

#185 µs ± 1.38 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
# Microseconds

如您所见,使用Numpy向量化函数可观的收益。有关它们的更多信息,请参见here

编辑

如果您实际使用值的numpy数组,则从矢量化中应该可以获得更好的性能:

df['Delivery_Point'] = get_if_str(df['Client_Num'].values, df['Entry_Point'].values)

答案 2 :(得分:0)

让我们使用熊猫to_numeric

df['New']=pd.to_numeric(df.Entry_Point,errors='coerce').fillna(df.Client_Num)
df
Out[22]: 
   Client_Num Entry_Point  New
0           1           0  0.0
1           2           a  2.0
2           3           3  3.0
3           4           4  4.0
4           5           b  5.0
5           6           c  6.0
6           8           d  8.0