redwolf_cr7
redwolf_cr7

Reputation: 2037

Pandas Dataframe: Create a new column and insert a value in a matching row based on two different columns

I have a pandas dataframe (say user_df) with 3 columns {"User_ID", "transaction_id","location"}. I want to create a new column "Amount" and enter a value in a row that matches "User_ID" and "location" columns. How do i do this?

  User_id transaction_id  location
0   User1             X1         0
1   User2             X1         0
2   User3             X1         2
3   User4             X2         1
4   User5             X2         2
5   User6             X2         1
6   User7             X3         2
7   User8             X3         2 

Upvotes: 1

Views: 1694

Answers (3)

M. Chavoshi
M. Chavoshi

Reputation: 1021

you'll have specified_amount for the columns with User1 and location '0' and for other cells, you'll have 0

df['Amount'] = np.where((user_df['User_id']== 'User1') & (user_df['location']==0), specified_amount, 0)

Upvotes: 1

Cks
Cks

Reputation: 314

Create a column 'Amount'

user_df['Amount'] = 0

user_df[(user_df['user_id] == 'xxxx') & (user_df['transaction_id'] == 'yyyy')]['amount'] = 'amount_value'

Upvotes: 0

niraj
niraj

Reputation: 18208

May be you can try using .loc with & for two columns, something like below:

user_df.loc[(user_df['User_id']== 'User1') & (user_df['location']==0), 'Amount'] = 100

Upvotes: 2

Related Questions