python - How do I add a new column and insert (calculated) data in one line? -


i'm pretty new python it's basic question.

i have data imported csv file. each row reflects person , data. 2 attributes sex , pclass. want add new column (predictions) depended on 2 in 1 line. if both attributes' values 1 should assign 1 person's predictions data field, 0 otherwise.

how do in 1 line (let's pandas)?

use:

np.random.seed(12) df = pd.dataframe(np.random.randint(3,size=(10,2)), columns=['sex','pclass'])  df['prediction'] = ((df['sex'] == 1) & (df['pclass'] == 1)).astype(int) print (df)    sex  pclass  prediction 0    2       1           0 1    1       2           0 2    0       0           0 3    2       1           0 4    0       1           0 5    1       1           1 6    2       2           0 7    2       0           0 8    1       0           0 9    0       1           0 

if values 1 , 0 use john galt solutions:

#only 0, 1 values df['predictions'] = df.all(axis=1).astype(int)  #if more possible values df['predictions'] = df.eq(1).all(axis=1).astype(int) print (df)    sex  pclass  predictions 0    2       1            0 1    1       2            0 2    0       0            0 3    2       1            0 4    0       1            0 5    1       1            1 6    2       2            0 7    2       0            0 8    1       0            0 9    0       1            0 

Comments

Popular posts from this blog

resizing Telegram inline keyboard -

command line - How can a Python program background itself? -

php - "cURL error 28: Resolving timed out" on Wordpress on Azure App Service on Linux -