Pandas – Create a DF with all the values from 2 columns

Question:

I have a DF similar to the below.
What I want to do is to take the SKUs from SKU1 and SKU2 and create a separate DF with all possible SKU values. It seems simple but I’m having some trouble.

DF

SKU1 SKU2
66FS 6dhs
b87w ssftv
yy5hf
y346d

Desired Output

All_SKUs
66FS
b87w
yy5hf
6dhs
ssftv
y346d
Asked By: PythonBeginner

||

Answers:

If order doesn’t matter, stack:

out = df.stack().droplevel(1).to_frame(name='All_SKUs')

output:

  All_SKUs
0     66FS
0     6dhs
1     b87w
1    ssftv
2    yy5hf
3    y346d

Else, melt:

out = df.melt(value_name='All_SKUs').dropna().drop(columns='variable')

output:

  All_SKUs
0     66FS
1     b87w
2    yy5hf
4     6dhs
5    ssftv
7    y346d
Answered By: mozway
pd.Series(df1.dropna().T.to_numpy().flatten(),name="All_SKUs")

output:

  All_SKUs
0     66FS
1     b87w
2    yy5hf
4     6dhs
5    ssftv
7    y346d
Answered By: G.G
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.