Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
374 views
in Technique[技术] by (71.8m points)

python - how to compare two columns in pandas to make a third column ?

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 ]

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' ]

please help ps . i am still working on it if i get anything i will immediately update

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use numpy.where:

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

The resulting output:

   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

Timings

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)})

I get the following timings:

%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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...