eugene
eugene

Reputation: 41785

pandas, assign multiple column values

I have user data in a df_user : only 1 row

user_id, age, height, item_id, item_height
1, 11, 15, 2, 3

I have df with same columns

user_id, age, height, item_id, item_height
2, 22, 33, 3, 4
5, 22, 33, 5, 4

Now I want to assign some columns (user_id, age, height) of df using the values of df_user

so the result would be

user_id, age, height, item_id, item_height
1, 11, 15, 3, 4
1, 11, 15, 5, 4

I'm currently thinking of the following, are their better one?

df = df.assign(user_id=df_user.user_id.values, age=df_user.age.values, height=df_user.height.values) 

Mainly, it's tedious to type those when you have more columns to copy..

Upvotes: 0

Views: 378

Answers (1)

jezrael
jezrael

Reputation: 863791

you can create Series by Index.get_indexer for positions by columns names and DataFrame.iloc for select by positions:

L = ['user_id', 'age', 'height']
df1 = df.assign(**df_user.iloc[0, df_user.columns.get_indexer(L)])

Or is possible use DataFrame.loc for select by labels:

L = ['user_id', 'age', 'height']
#if index is 0
#df1 = df.assign(**df_user.loc[0, L])
#general index
df1 = df.assign(**df_user.loc[df_user.index[0], L])

print (df1)
   user_id  age  height  item_id  item_height
0        1   11      15        3            4
1        1   11      15        5            4

Upvotes: 2

Related Questions