1

I have input dataset like the first image. I want to map the columns to one other. I want the output in format given in second image. If I explode the columns it is showing both values. What is the accurate way to do this? Suppose I have input like this

I want the output to be like another image using pandas

  • 1
    Welcome to Stackoverflow. Please [don't post images of code/data](https://meta.stackoverflow.com/questions/285551/why-not-upload-images-of-code-errors-when-asking-a-question) instead add them in text format so that we could be able to copy these while trying to answer the question. Please take some time to read [How to ask good pandas questions?](https://stackoverflow.com/questions/20109391/how-to-make-good-reproducible-pandas-examples) – Shubham Sharma Apr 17 '21 at 10:38

1 Answers1

1

You can use itertools.zip_longest:

from itertools import zip_longest

print(
    pd.DataFrame(
        df.apply(lambda x: [*zip_longest(*x, fillvalue=np.nan)], axis=1)
        .explode()
        .to_list(),
        columns=df.columns,
    )
)

Prints:

     A  B
0  abc  1
1  NaN  2
2  pqr  3
3  xyz  4
Andrej Kesely
  • 168,389
  • 15
  • 48
  • 91