给定这个数据框,
A = pd.DataFrame([[1, 5, 2], [2, 4, 4], [3, 3, 1], [4, 2, 2], [5, 1, 4]],
columns=['A', 'B', 'C'], index=[1, 2, 3, 4, 5])
我想根据大小对“A”列的元素进行分类,并创建一个新列,输出如下:
In [26]: A['Size'] = ""
for index, row in A.iterrows():
if row['A'] >= 4:
A.loc[index, 'Size'] = 'Big'
if 2.5 < row['A'] < 4:
A.loc[index, 'Size'] = 'Medium'
if 0 < row['A'] < 2.4:
A.loc[index, 'Size'] = 'Small'
输出将是:
Out[27]:
A B C Size
1 1 5 2 Small
2 2 4 4 Small
3 3 3 1 Medium
4 4 2 2 Big
5 5 1 4 Big
想象一下,对于相同的类别,您有很多列和不同的参数,是否有更有效的方法来做到这一点?
谢谢
请您参考如下方法:
您可以使用 loc 作为 bool 掩码来仅分配给满足条件的行,即使对于这么小的 df 它也更快,对于更大的 df 它会明显更快:
In [60]:
%%timeit
A['Size'] = ""
for index, row in A.iterrows():
if row['A'] >= 4:
A.loc[index, 'Size'] = 'Big'
if 2.5 < row['A'] < 4:
A.loc[index, 'Size'] = 'Medium'
if 0 < row['A'] < 2.4:
A.loc[index, 'Size'] = 'Small'
100 loops, best of 3: 2.31 ms per loop
In [62]:
%%timeit
A.loc[A['A'] >=4, 'Size'] = 'Big'
A.loc[(A['A'] >= 2.5) & (A['A'] < 4), 'Size'] = 'Medium'
A.loc[A['A'] < 2.4, 'Size'] = 'Small'
100 loops, best of 3: 1.95 ms per loop
此外,您可以使用 3 个 np.where 条件,这会更快:
In [64]:
%%timeit
A['Size'] = np.where(A['A'] < 2.4, 'Small', np.where((A['A'] >= 2.5) & (A['A'] < 4), 'Medium', np.where(A['A'] >=4, 'Big','')))
1000 loops, best of 3: 828 µs per loop
更新
有趣的是,对于 50,000 行的数据帧,loc 方法优于嵌套的 np.where 方法:我得到 4.24 毫秒对 12.1 毫秒。
