0

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..

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

1 Comment

since iloc needs 0-based index, get_indexer must give 0 based index for column, loc uses label of index.. so index[0] must give label of index at 0 position.. great to know..thanks

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.