Python 如何比较pandas中的两列以生成第三列?
我在熊猫数据框中有两列“年龄”和“性别”Python 如何比较pandas中的两列以生成第三列?,python,pandas,Python,Pandas,我在熊猫数据框中有两列“年龄”和“性别” sex = ['m', 'f' , 'm', 'f', 'f', 'f', 'f'] age = [16 , 15 , 14 , 9 , 8 , 2 , 56 ] 现在我想提取第三列:像这样 如果是9岁,则输出相应的性别 sex = ['m', 'f' , 'm','f' ,'f' ,'f' , 'f'] age = [16 , 15 , 14 , 9 , 8 , 2 , 56 ] yes =
sex = ['m', 'f' , 'm', 'f', 'f', 'f', 'f']
age = [16 , 15 , 14 , 9 , 8 , 2 , 56 ]
现在我想提取第三列:像这样
如果是9岁,则输出相应的性别
sex = ['m', 'f' , 'm','f' ,'f' ,'f' , 'f']
age = [16 , 15 , 14 , 9 , 8 , 2 , 56 ]
yes = ['m', 'f' ,'m' ,'child','child','child','f' ]
请帮忙
附言我仍在努力,如果我得到任何信息,我将立即更新使用:
计时
使用以下设置获取更大的示例数据帧:
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
%timeit np.where(df['age']9'child')
100个回路,最佳3个:每个回路3.25毫秒
%timeit df.apply(lambda x:'child'如果x['age']您可以使用。例如
child.where(age<=9, sex)
child.where(agethis像这个np.where(condition,if-do-this,els-do-this)一样工作吗?是的,这看起来很好用,虽然df.apply看起来很直观:)这里的语法不正确。如果你想使用DataFrame.where
,它应该是这样的:df['sex'].where(df['age']>9'child')
。
%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
child.where(age<=9, sex)
df = pd.DataFrame({'sex':['m', 'f' , 'm', 'f', 'f', 'f', 'f'],
'age':[16, 15, 14, 9, 8, 2, 56]})
df['yes'] = df.apply(lambda x: 'child' if x['age'] <= 9 else x['sex'], axis=1)
age sex yes
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