下面我有一个 4 人消费的小数据框。 有一个名为“等级”的空列。 我想将花费超过 100 美元的人评为 A 级,将花费少于 100 美元的人评为 B 级。 假设它是一个大数据框,填充“等级”列的最有效方法是什么?
import pandas as pd
df=pd.DataFrame({'Customer':['Bob','Ken','Steve','Joe'],
'Spending':[130,22,313,46]})
df['Grade']=''
最佳答案
您可以使用numpy.where
:
df['Grade']= np.where(df['Spending'] > 100 ,'A','B')
print (df)
Customer Spending Grade
0 Bob 130 A
1 Ken 22 B
2 Steve 313 A
3 Joe 46 B
时间:
df=pd.DataFrame({'Customer':['Bob','Ken','Steve','Joe'],
'Spending':[130,22,313,46]})
#[400000 rows x 4 columns]
df = pd.concat([df]*100000).reset_index(drop=True)
In [129]: %timeit df['Grade']= np.where(df['Spending'] > 100 ,'A','B')
10 loops, best of 3: 21.6 ms per loop
In [130]: %timeit df['grade'] = df.apply(lambda row: 'A' if row['Spending'] > 100 else 'B', axis = 1)
1 loop, best of 3: 7.08 s per loop
关于python pandas - 将值输入到新列中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41165818/