1

Imagine I have dataframe

   A B C id
0  1 2 3 1
1  2 3 4 1

given list of values for id, for example [1,2,3] how can I obtain

   A B C id
0  1 2 3 1
1  2 3 4 1
2  1 2 3 2
3  2 3 4 2
4  1 2 3 3
5  2 3 4 3

in a most convenient and efficient way?

2 Answers 2

1

Try repeat the index, then repeat the id list:

id_list = [1,2,3]

(df.loc[df.index.repeat(len(id_list))]
   .assign(id=np.repeat(id_list, len(df)))
)

Output:

   A  B  C  id
0  1  2  3   1
0  1  2  3   1
0  1  2  3   2
1  2  3  4   2
1  2  3  4   3
1  2  3  4   3
Sign up to request clarification or add additional context in comments.

Comments

1

Another technique (just for learning purpose, not efficient):

concat and then multiple the id with list element after grouping them together.

idx = [1,2,3]
y = pd.concat([df]*len(idx))
y.assign(id=y.groupby(y.index)['id'].transform(lambda x:x.mul(idx))).reset_index(drop=True)

A B C id
0 1 2 3 1
1 2 3 4 1
2 1 2 3 2
3 2 3 4 2
4 1 2 3 3
5 2 3 4 3

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.