2016-08-12 72 views
4

我有两列年龄和性别的熊猫数据帧如何比较熊猫中的两列制作第三列?

sex = ['m', 'f' , 'm', 'f', 'f', 'f', 'f'] 
age = [16 , 15 , 14 , 9 , 8 , 2 , 56 ] 

现在我想提取第三列:这样 如果年龄< = 9,然后输出的“孩子”,如果年龄> 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' ] 

请帮忙 ps。我仍然在做这个工作,如果我得到什么,我会立即更新

回答

9

使用numpy.where

df['col3'] = np.where(df['age'] <= 9, 'child', df['sex']) 

输出结果:

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:

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 
+0

这是这样工作np.where(条件,如果做到这一点,否则这样做)? –

+0

是的,这是正确的。 – root

+0

这似乎很好用,虽然df.apply看起来很直观:) –

4

你可以使用pandas.DataFrame.where。例如

child.where(age<=9, sex) 
+1

这里的语法不正确。如果你想使用'DataFrame.where',它应该是这样的:'df ['sex']。where(df ['age']> 9,'child')'。 – root

2
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