我有以下 Pandas 数据框:
import pandas as pd
import numpy as np
d = {'age' : [21, 45, 45, 5],
'salary' : [20, 40, 10, 100]}
df = pd.DataFrame(d)
并想添加一个名为“is_rich”的额外列,根据他/她的薪水捕获一个人是否富有。我找到了多种方法来实现这一点:
# method 1
df['is_rich_method1'] = np.where(df['salary']>=50, 'yes', 'no')
# method 2
df['is_rich_method2'] = ['yes' if x >= 50 else 'no' for x in df['salary']]
# method 3
df['is_rich_method3'] = 'no'
df.loc[df['salary'] > 50,'is_rich_method3'] = 'yes'
导致:
但是我不明白首选的方式是什么。根据您的应用,所有方法都一样好吗?
最佳答案
使用 timeits
,卢克!
结论
列表推导式在较小数量的数据上表现最好,因为它们产生的开销很小,即使它们没有被矢量化。 OTOH,在更大的数据上,loc
和 numpy.where
表现更好 - 矢量化赢得了胜利。
请记住,方法的适用性取决于您的数据、条件数量和列的数据类型。我的建议是在选择一个选项之前,对您的数据测试各种方法。
然而,从这里可以肯定的是,列表理解非常有竞争力——它们是用 C 语言实现的,并且针对性能进行了高度优化。
Benchmarking code, for reference .以下是正在计时的函数:
def numpy_where(df):
return df.assign(is_rich=np.where(df['salary'] >= 50, 'yes', 'no'))
def list_comp(df):
return df.assign(is_rich=['yes' if x >= 50 else 'no' for x in df['salary']])
def loc(df):
df = df.assign(is_rich='no')
df.loc[df['salary'] > 50, 'is_rich'] = 'yes'
return df
关于python - Pandas 根据其他列的条件添加具有值的列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50375985/