如何比较 pandas 中的两列以构成第三列? [英] how to compare two columns in pandas to make a third column ?
本文介绍了如何比较 pandas 中的两列以构成第三列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在熊猫数据框中有两列年龄和性别
i have two columns age and sex in a pandas dataframe
sex = ['m', 'f' , 'm', 'f', 'f', 'f', 'f']
age = [16 , 15 , 14 , 9 , 8 , 2 , 56 ]
现在我要提取第三列:像这样 如果年龄< = 9,则输出'child',如果年龄> 9,则输出相应的性别
now i want to extract a third column : like this if age <=9 then output ' child' and if age >9 then output the respective gender
sex = ['m', 'f' , 'm','f' ,'f' ,'f' , 'f']
age = [16 , 15 , 14 , 9 , 8 , 2 , 56 ]
yes = ['m', 'f' ,'m' ,'child','child','child','f' ]
请帮助 ps.如果我得到任何帮助,我仍在努力,我会立即更新
please help ps . i am still working on it if i get anything i will immediately update
推荐答案
使用结果输出:
age sex col3
0 16 m m
1 15 f f
2 14 m m
3 9 f child
4 8 f child
5 2 f child
6 56 f f
时间
使用以下设置来获取更大的示例DataFrame:
Using the following setup to get a larger sample DataFrame:
np.random.seed([3,1415])
n = 10**5
df = pd.DataFrame({'sex': np.random.choice(['m', 'f'], size=n), 'age': np.random.randint(0, 100, size=n)})
我得到以下计时:
%timeit np.where(df['age'] <= 9, 'child', df['sex'])
1000 loops, best of 3: 1.26 ms per loop
%timeit df['sex'].where(df['age'] > 9, 'child')
100 loops, best of 3: 3.25 ms per loop
%timeit df.apply(lambda x: 'child' if x['age'] <= 9 else x['sex'], axis=1)
100 loops, best of 3: 3.92 ms per loop
这篇关于如何比较 pandas 中的两列以构成第三列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文